原文: https://www.gurustop.net/blog/2014/01/28/common-problems-and-solutions-when-using-select-elements-with-angular-js-ng-options-initial-selection/

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

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

<code><select ng-model="myModel.someObject"
ng-options="someObject.text for someObject in objectList ">
</select>
</code>
 

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.

<code><select ng-model="myModel.someObject"
ng-options="someObject.text for someObject in objectList track by someObject.key">
</select>
</code>
 

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:

<code><select
ng-model="person.genderId"
ng-options="gender.id as gender.text for gender in genders">
</select>
</code>
 

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.

<code><select
ng-init="person._gender = {id: person.genderId}"
ng-change="person.genderId = person._gender.id"
ng-model="person._gender"
ng-options="gender.id as gender.text
for gender in genders track by gender.id">
</select>
</code>
 

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 here.

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!

<code><select ng-model="myModel.someObject"
ng-options="someObject.text for someObject in
objectList track by someObject.key">
<option value="">-- Select an option--</option>
</select>
</code>
 

Update:

If you are using Angular 1.4+, check the much smaller 2nd part of this article, about how to use track by correctly.
Using track by correctly with Angular 1.4 select ng-options – Why can’t I select this option?

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:

How to set the initial value of a select element using AngularJS ng-options & track by的更多相关文章

  1. 使控件具有 Tilt 效果

    步骤1:添加类: /* Copyright (c) 2010 Microsoft Corporation. All rights reserved. Use of this sample source ...

  2. Django之Form组件

    Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功能: 生成HTML标签 验证用户 ...

  3. ABAP 订单-交货单-发货过账自动完成 案例

    *&---------------------------------------------------------------------* *& Report  ZSDR006 ...

  4. SAP 订单状态跟踪

    *&--------------------------------------------------------------------- *& Program name:  *& ...

  5. 【Django】--Form组件

    Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 例子: 1.创建Form类 from djan ...

  6. ABAP 订单转交货单

    *& Report  ZSDR025 *& *&---------------------------------------------------------------- ...

  7. jqGrid配置属性说明

    Property Type Description Default1) ajaxGridOptions object This option allows to set global ajax set ...

  8. django--forms

    forms模块的功能 1 表单提交验证 2 生成HTML标签 其他 提交后保留页面数据 创建forms类 首先从django中引入forms,一般会在application中新建一个文件专门保存for ...

  9. javascript 手势缩放 旋转 拖动支持:hammer.js

    原文: https://cdn.rawgit.com/hammerjs/hammer.js/master/tests/manual/visual.html /*! Hammer.JS - v2.0.4 ...

随机推荐

  1. Leetcode21--->Merge Two Sorted Lists(合并两个排序的单链表)

    题目: 给出两个排序的单链表,合并两个单链表,返回合并后的结果: 解题思路: 解法还是很简单的,但是需要注意以下几点: 1.  如果两个链表都空,则返回null; 2.  如果链表1空,则返回链表2的 ...

  2. python + selenium - selenium简介

    1. 产品简介 selenium 是 基于 web网页的UI自动化测试框架. 1)支持多浏览器操作:ie.chrome.firefox.edge.safaria等 2)跨平台:windows.linu ...

  3. SDOJ 3740 Graph

    8.9 t3 [描述] 给你一个图,一共有 N 个点,2*N-2 条有向边. 边目录按两部分给出 1. 开始的 n-1 条边描述了一颗以 1 号点为根的生成树,即每个点都可以由 1 号点 到达. 2. ...

  4. 面试中注意3个javascript的问题

    JavaScript 是所有现代浏览器的官方语言.因此,各种语言的开发者面试中都会遇到 JavaScript 问题. 本文不讲最新的 JavaScript 库,通用开发实践,或任何新的 ES6 函数. ...

  5. xml报错“cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element”

    配置使用dubbo时,xml报错“cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be ...

  6. cURL介绍

    1.cURL介绍 cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP.FTP.TELNET等.最爽的是,PHP也支持 cURL 库.本文将介绍 cURL 的一些高级特性 ...

  7. 【bzoj2561】最小生成树 网络流最小割

    题目描述 给定一个边带正权的连通无向图G=(V,E),其中N=|V|,M=|E|,N个点从1到N依次编号,给定三个正整数u,v,和L (u≠v),假设现在加入一条边权为L的边(u,v),那么需要删掉最 ...

  8. HDU——2064汉诺塔III

    汉诺塔III Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Sub ...

  9. bzoj 1572: [Usaco2009 Open]工作安排Job

    Description Farmer John 有太多的工作要做啊!!!!!!!!为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间. 他的工作日从0时刻开始,有1000000000个单 ...

  10. BZOJ3160 万径人踪灭 【fft + manacher】

    题解 此题略神QAQ orz po神牛 由题我们知道我们要求出: 回文子序列数 - 连续回文子串数 我们记为ans1和ans2 ans2可以用马拉车轻松解出,这里就不赘述了 问题是ans1 我们设\( ...