以下是困扰很多人(包括我)的问题。
当在AngularJS中使用ng-options指令来填充<select>标记的选项时,我不知道如何为一个选项设置值。这方面的文档确实不清楚——至少对我这样的傻瓜来说是这样。
我可以像这样轻松地设置一个选项的文本:
ng-options="select p.text for p in resultOptions"
例如,当resultOptions为:
[
{
"value": 1,
"text": "1st"
},
{
"value": 2,
"text": "2nd"
}
]
它应该是(可能是)设置选项值最简单的事情,但到目前为止,我只是不明白它。
就像很多人之前说的,如果我有这样的数据:
countries : [
{
"key": 1,
"name": "UAE"
},
{
"key": 2,
"name": "India"
},
{
"key": 3,
"name": "OMAN"
}
]
我会这样使用它:
<select
ng-model="selectedCountry"
ng-options="obj.name for obj in countries">
</select>
在你的控制器中,你需要设置一个初始值来消除第一个空项:
$scope.selectedCountry = $scope.countries[0];
// You need to watch changes to get selected value
$scope.$watchCollection(function() {
return $scope.selectedCountry
}, function(newVal, oldVal) {
if (newVal === oldVal) {
console.log("nothing has changed " + $scope.selectedCountry)
}
else {
console.log('new value ' + $scope.selectedCountry)
}
}, true)
以下是我如何在遗留应用程序中解决这个问题:
在HTML中:
ng-options="kitType.name for kitType in vm.kitTypes track by kitType.id" ng-model="vm.itemTypeId"
在JavaScript中:
vm.kitTypes = [
{"id": "1", "name": "Virtual"},
{"id": "2", "name": "Physical"},
{"id": "3", "name": "Hybrid"}
];
...
vm.itemTypeId = vm.kitTypes.filter(function(value, index, array){
return value.id === (vm.itemTypeId || 1);
})[0];
我的HTML正确地显示了选项值。
开发人员使用ng-options总是很痛苦的。例如:在select标记中获取空/空的选定值。特别是在ng-options中处理JSON对象时,它变得更加乏味。这里我已经做了一些练习。
目的:通过ng-option迭代JSON对象数组,并设置选中的第一个元素。
数据:
someNames = [{"id":"1", "someName":"xyz"}, {"id":"2", "someName":"abc"}]
在选择标签中,我必须显示xyz和abc,其中xyz必须毫不费力地选择。
HTML:
<pre class="default prettyprint prettyprinted" style=""><code>
<select class="form-control" name="test" style="width:160px" ng-options="name.someName for name in someNames" ng-model="testModel.test" ng-selected = "testModel.test = testModel.test || someNames[0]">
</select>
</code></pre>
通过上面的代码示例,您可能会摆脱这种夸张。
另一个参考: