以下是困扰很多人(包括我)的问题。
当在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。
运行代码片段并查看变化。为了快速理解,这里有一个注释
例1(对象选择):- ng-option="os.name for os in osList track by os.id"。这里由os跟踪。Id是重要的&应该在那里和os。id不应该出现在os.name之前。
ng-model="my_os"应该设置为一个key为id的对象,例如my_os={id: 2}。
例2(取值选择):- ng-option="os. "id作为osList中os的os.name”。这里由os跟踪。id不应该在那里,os。Id应该在os.name之前。
ng-model="my_os"应该设置为my_os= 2这样的值
其余代码片段将进行解释。
angular.module('app', []).controller('ctrl', function($scope, $timeout){
//************ EXAMPLE 1 *******************
$scope.osList =[
{ id: 1, name :'iOS'},
{ id: 2, name :'Android'},
{ id: 3, name :'Windows'}
]
$scope.my_os = {id: 2};
//************ EXAMPLE 2 *******************
$timeout(function(){
$scope.siteList = [
{ id: 1, name: 'Google'},
{ id: 2, name: 'Yahoo'},
{ id: 3, name: 'Bing'}
];
}, 1000);
$scope.my_site = 2;
$timeout(function(){
$scope.my_site = 3;
}, 2000);
})
fieldset{
margin-bottom: 40px;
}
strong{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.10/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<!--//************ EXAMPLE 1 *******************-->
<fieldset>
<legend>Example 1 (Set selection as <strong>object</strong>)</legend>
<select ng-model="my_os" ng-options="os.name for os in osList track by os.id">
<option value="">--Select--</option>
</select>
{{my_os}}
</fieldset>
<!--//************ EXAMPLE 2 *******************-->
<fieldset>
<legend>Example 2 (Set selection as <strong>value</strong>. Simulate ajax)</legend>
<select ng-model="my_site" ng-options="site.id as site.name for site in siteList">
<option value="">--Select--</option>
</select>
{{my_site}}
</fieldset>
</div>
ng-options看起来使用起来很复杂(可能令人沮丧),但实际上我们有一个架构问题。
AngularJS是动态HTML+JavaScript应用程序的MVC框架。虽然它的(V)视图组件确实提供了HTML“模板”,但它的主要目的是通过控制器将用户操作连接到模型中的更改。因此,在AngularJS中,适当的抽象级别是select元素将模型中的值设置为来自查询的值。
查询行如何呈现给用户是(V)视图关心的问题,ng-options提供了for关键字来指示选项元素的内容应该是什么,即p.text for resultOptions中的p。
所选的行如何呈现给服务器是(M)模型所关心的。因此ng-options提供了as关键字来指定在对象中(k,v)的k和v中向模型提供什么值。
这个问题的正确解决方案是本质上的体系结构,并涉及重构HTML,以便(M)模型在需要时执行服务器通信(而不是用户提交表单)。
如果一个MVC HTML页面对于手头的问题来说是不必要的过度工程:那么只使用AngularJS的(V)视图组件的HTML生成部分。在这种情况下,遵循与生成<ul />'s下的<li />'s相同的模式,并在一个选项元素上放置ng-repeat:
<select name=“value”>
<option ng-repeat=“value in Model.Values” value=“{{value.value}}”>
{{value.text}}
</option>
</select>
作为临时拼凑,我们总是可以将选择元素的name属性移动到一个隐藏的输入元素:
<select ng-model=“selectedValue” ng-options=“value.text for value in Model.Values”>
</select>
<input type=“hidden” name=“value” value=“{{selectedValue}}” />
对我来说,布鲁诺·戈麦斯的答案是最好的答案。
但实际上,您不需要担心设置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或任何其他库来访问选择组合框选项的值并相应地操作它。