这里有一些快速的背景信息。我刚刚升级到 Angular 1.4。我正在使用用 C# 编写的 API 进行服务器端调用。
我页面的一部分显示了 2 个选择列表(项目和子项目)。两者都应该默认为“(Select a ______)”,我将其列为每个选择的第一个选项,“值”为 0。适当的 ng-model 变量被初始化为 0。
选择列表的实际 HTML 代码是在服务器端使用字符串连接生成的,通过 $http 传递给客户端,并使用调用 $compile 的指令插入(一点也不理想,但我的客户端有漂亮的很多链接我到这个API)。在 1.4 更新之前,一切都运行良好。
现在,我的项目选择列表默认为空。当我检查元素时,这就是我所看到的...
<select ng-change="updateSubProjList()" ng-model="curProjID">
<option value="? number:0 ?"></option>
<option value="0">(Select a Project)</option>
<option value="1">First Project</option>
<option value="2">Second Project</option>
...
</select>
...第一个 "? number:0 ?"条目是当前选择的条目。我的子项目选择列表仍然初始化得很好,这让这更奇怪了。
我知道在 AngularJS 1.4 的更新中对 $compile 进行了一些更新,但我无法找到解决我的问题的方法。如有任何帮助,我们将不胜感激。
最佳答案
在 1.4 中似乎有一个变化与所选选项与 ngModel 的匹配方式有关。通过比较 value <option value="0"> 中的属性- 现在需要明确使用字符串进行匹配,而不是允许使用整数。
事实上,documentation明确指出:
The value of a
selectdirective used withoutngOptionsis always a string. When the model needs to be bound to a non-string value, you must either explicitly convert it using a directive ... or usengOptionsto specify the set of options.
要修复,请更改 $scope.curProjID 的初始值成为一个字符串:
$scope.curProjID = "0"; // instead of $scope.curProjID = 0;
当没有匹配项时(也没有,除非你分配一个字符串 "0" ),select添加一个“未知”选项:<option value="? number:0 ?"></option> .
关于javascript - AngularJS 1.4 : Select List Value not Initializing Correctly when List is Inserted with $compile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30582906/