以下是困扰很多人(包括我)的问题。
当在AngularJS中使用ng-options指令来填充<select>标记的选项时,我不知道如何为一个选项设置值。这方面的文档确实不清楚——至少对我这样的傻瓜来说是这样。
我可以像这样轻松地设置一个选项的文本:
ng-options="select p.text for p in resultOptions"
例如,当resultOptions为:
[
{
"value": 1,
"text": "1st"
},
{
"value": 2,
"text": "2nd"
}
]
它应该是(可能是)设置选项值最简单的事情,但到目前为止,我只是不明白它。
在ng-options中选择一个项目可能有点棘手,这取决于您如何设置数据源。
在与它们斗争了一段时间后,我最终用我使用的最常用的数据源制作了一个样本。你可以在这里找到它:
http://plnkr.co/edit/fGq2PM?p=preview
现在要让ng-options工作,需要考虑以下几点:
Normally you get the options from one source and the selected value from other. For example:
states :: data for ng-options
user.state :: Option to set as selected
Based on 1, the easiest/logical thing to do is to fill the select with one source and then set the selected value trough code. Rarely would it be better to get a mixed dataset.
AngularJS allows select controls to hold more than key | label. Many online examples put objects as 'key', and if you need information from the object set it that way, otherwise use the specific property you need as key. (ID, CODE, etc.. As in the plckr sample)
The way to set the value of the dropdown/select control depends on #3,
If the dropdown key is a single property (like in all examples in the plunkr), you just set it, e.g.:
$scope.dropdownmodel = $scope.user.state;
If you set the object as key, you need to loop trough the options, even assigning the object will not set the item as selected as they will have different hashkeys, e.g.:
for (var i = 0, len = $scope.options.length; i < len; i++) {
if ($scope.options[i].id == savedValue) { // Your own property here:
console.log('Found target! ');
$scope.value = $scope.options[i];
break;
}
}
您可以在另一个对象$scope.myObject.myProperty中替换相同属性的savedValue。
一年后,我不得不找到这个问题的答案,因为这些问题都没有给出实际答案,至少对我来说是这样。
你问过如何选择选项,但没有人说这两件事不一样:
如果我们有这样的选项:
$scope.options = [
{ label: 'one', value: 1 },
{ label: 'two', value: 2 }
];
我们试着像这样设置一个默认选项:
$scope.incorrectlySelected = { label: 'two', value: 2 };
它不会工作,但如果你尝试选择这样的选项:
$scope.correctlySelected = $scope.options[1];
它会起作用的。
尽管这两个对象具有相同的属性,AngularJS仍然将它们视为DIFFERENT,因为AngularJS是通过引用进行比较的。
看看小提琴http://jsfiddle.net/qWzTb/。
对我来说,布鲁诺·戈麦斯的答案是最好的答案。
但实际上,您不需要担心设置select options的value属性。AngularJS会处理这个。让我详细解释一下。
请考虑这把小提琴
angular.module('mySettings', []).controller('appSettingsCtrl', function ($scope) {
$scope.timeFormatTemplates = [{
label: "Seconds",
value: 'ss'
}, {
label: "Minutes",
value: 'mm'
}, {
label: "Hours",
value: 'hh'
}];
$scope.inactivity_settings = {
status: false,
inactive_time: 60 * 5 * 3, // 15 min (default value), that is, 900 seconds
//time_format: 'ss', // Second (default value)
time_format: $scope.timeFormatTemplates[0], // Default seconds object
};
$scope.activity_settings = {
status: false,
active_time: 60 * 5 * 3, // 15 min (default value), that is, 900 seconds
//time_format: 'ss', // Second (default value)
time_format: $scope.timeFormatTemplates[0], // Default seconds object
};
$scope.changedTimeFormat = function (time_format) {
'use strict';
console.log('time changed');
console.log(time_format);
var newValue = time_format.value;
// do your update settings stuffs
}
});
正如你在fiddle输出中看到的,无论你为选择框选项选择了什么,它都是你的自定义值,或者AngularJS自动生成的0、1、2值,这在你的输出中并不重要,除非你使用jQuery或任何其他库来访问选择组合框选项的值并相应地操作它。
这个问题的正确答案由用户frm提供。Adiputra,因为目前这似乎是显式控制选项元素的value属性的唯一方法。
然而,我只是想强调,“select”在这里不是关键字,而只是表达式的占位符。请参考以下列表,“select”表达式的定义以及ng-options指令中可以使用的其他表达式。
问题中描述的select的用法:
ng-options='select p.text for p in resultOptions'
本质上是错误的。
根据表达式列表,当在对象数组中给出选项时,似乎可以使用trackexpr来指定值,但它仅用于分组。
来自AngularJS的ng-options文档:
array / object: an expression which evaluates to an array / object to
iterate over.
value: local variable which will refer to each item in
the array or each property value of object during iteration.
key: local variable which will refer to a property name in object during
iteration.
label: The result of this expression will be the label for
element. The expression will most likely refer to the value
variable (e.g. value.propertyName).
select: The result of this expression will be bound to the model of the parent element.
If not specified, select expression will default to value.
group: The result of this expression will be used to group options using the DOM
element.
trackexpr: Used when working with an array of objects. The result of this expression will be used
to identify the objects in the array. The trackexpr will most likely refer to the
value variable (e.g. value.propertyName).
以下是我如何在遗留应用程序中解决这个问题:
在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正确地显示了选项值。