博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How to set the initial value of a select element using AngularJS ng-options & track by
阅读量:5815 次
发布时间:2019-06-18

本文共 5267 字,大约阅读时间需要 17 分钟。

原文: 

 

------------------------------------------------------------------------------------------------------------------------

I have been doing Angular.JS in production projects for months, that it did surprise me recently how I haven’t used drop-downs in it. Well, I mean how I haven’t used them enough to get into several problems I had in my current project, and other friends at the same office had in their project as well.

To save you the pain I went through, I’ll list some problems and solutions here, and then give you a video that shows going through all of them ans the thought process that led to the solutions.

 

Initial selection

 
 

Assuming someObject in the model has the same properties and values as someObject in the objectList, it will still not be selected.

It’ll only be selected if someObject was actually one of the objects in objectList, like objectList[0] or whatever. Otherwise, Angular.JS will insert an empty option tag with no value or text and select that.

Root Cause

Angular.JS uses native JavaScript comparison for comparing the objects. In JavaScript, unrelated to Angular.JS or anything, comparing objects (object literals) is “by reference”, so it doesn’t factor the similarity of the objects. Only checks if the two references compared point to the same object in memory or not.

Solution

An un-documented (AFAIK) feature in ng-options is that you can use some bits from the ng-repeat directive with it, like track by. This allows us to choose some property as the comparison key.

 
 

If the key property is a simple type, like Number or string, JavaScript will consider it equal to any other object that has the same value, so we don’t have to use the same objects.

Invalid Value Sent On Server-Side Submit

When Angular.JS writes the <option> tags from an ng-options directive pointing to an array, the value of the option is always the index of the element it maps to in the array. This is not important if you process the selection on client side because you only deal with the result of ng-model anyway, you can use this later to create an AJAX request or whatever.

However, if you intend to submit the form using a normal server submission, and only use Angular.JS for say validation or managing complex form interaction (client-side tables containing sub-items with add/remove/sort for example), this may be a road blocker to using Angular.

Root Cause

By default Angular.JS uses the index of the array to track which object maps to which <option> element.

Solution

Similar to the previous problem, use the track by syntax. Angular.JS will use the track by property value as the <option>‘s value. Most of the time your tracked property is the key property you want to send to the server anyway, so, this should be good enough.

Simple Properties Scenario When Combined With Server-Side Submit

Let’s say you want something as simple as this:

 
 

This syntax will work very well, if you only use this value from JavaScript, you are all set. But if you plan to send it directly to the server (a normal non-AJAX form submit), you’ll want to consider using the track by syntax, like track by gender.id.

However, if you do this, you’ll notice that the select is no longer usable. No initial selection, and changing selection although updates the model, it does not show the new selected value.

Root Cause

The track by syntax expects an object, with the property you use to track. It does not honor the key part used in the key as text syntax (which in our example is g.id as g.text), so, it wants the ng-model to point to an object with the tracked property, it cannot be the key itself directly.

Workaround

I didn’t call this a solution, because it’s pretty much a hack.

 
 

We created a new property (which I liked to prefix with _ to show it doesn’t normally belong to the model object), initialized it to a new object that contains only our key property id set to the original simple value genderId, and then used that as the model (as in ng-model).

We created and assigned the property in ng-init, then synchronized the changes to the simple property via ng-change. This allows the code everywhere else in the application (like the controller, or other parts of the markup) to only interact with the property we want (genderId in this example), without knowing about our hack. This makes things a bit cleaner, although it still remains a hack rather than a solution.

You can view an example of using this hack .

Adding extra selection items to the dropdown

One thing you notice if you are affected by the “initial selection” problem, is that the empty <option> tag that Angular.JS adds when it can’t match the ng-model to the array from ng-options disappears when the use changes their selection. We have gone through how to avoid showing the empty option by mistake already.

But if you do want to have that option, it’s easy, just, um, add it!

 
 

Update:

If you are using Angular 1.4+, check the much smaller 2nd part of this article, about how to use track by correctly.

The Video

If you want to dig these problems really deep and see what they look like in action, and what was the thought process for solving them like and in some cases other possible solutions, I have put all this in a (rather long) video here:

转载地址:http://fgmbx.baihongyu.com/

你可能感兴趣的文章
Lua中的元表与元方法
查看>>
Servlet&jsp基础:第三部分
查看>>
Ubuntu12.04LTS安装好后是空白桌面的解决步骤(更新显卡驱动)
查看>>
poj-3696 The Luckiest number
查看>>
[Dynamic Language] Python定时任务框架
查看>>
Furure的简单介绍和使用
查看>>
CSS3 网格布局(grid layout)基础知识 - 隐式网格自己主动布局(grid-auto-rows/grid-auto-columns/grid-auto-flow)...
查看>>
构建Docker Compose服务堆栈
查看>>
最小角回归 LARS算法包的用法以及模型参数的选择(R语言 )
查看>>
CentOS7下zip解压和unzip压缩文件
查看>>
Hadoop生态圈-Kafka常用命令总结
查看>>
如何基于Redis Replication设计并实现Redis-replicator?
查看>>
Linux 环境下 PHP 扩展的编译与安装 以 mysqli 为例
查看>>
php防止会话固定攻击
查看>>
openmp在图像处理上面的运用
查看>>
Key Components and Internals of Spring Boot Framework--转
查看>>
基于Bootstrap的jQuery开关按钮插件
查看>>
修改linux文件权限命令:chmod
查看>>
如何删除PHP数组中的元素,并且索引重排(unset,array_splice)?
查看>>
Python数据分析:手写数字识别初步
查看>>