需要注意的一点是,ngModel是required,用于ngOptions的...注意ng-model="blah"
,它表示"将$scope.blah设置为所选值".
试试这个:
<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>
以下是AngularJS文档中的更多内容(如果您没有看到):
对于数组数据源:
- 数组中值的标签
- select as 数组中值的标签
- 数组中值的GROUP BY GROUP标签
=为数组中的值 Select 作为标签GROUP BY GROUP
对于对象数据源:
- 对象中(键、值)的标签
- select as 对象中(键、值)的标签
- 对象中按GROUP FOR(关键点、值)分组的标签
- select as 对象中按GROUP FOR(关键点、值)分组的标签
有关AngularJS中选项标记值的一些说明:
当你用ng-options
,the values of option tags written out by ng-options will always be the index of the array item the option tag relates to的时候.这是因为AngularJS实际上允许您使用 Select 控件 Select 整个对象,而不仅仅是基本类型.例如:
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }
];
});
<div ng-controller="MainCtrl">
<select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<pre>{{selectedItem | json}}</pre>
</div>
以上将允许您直接 Select $scope.selectedItem
中的整个对象.The point is, with AngularJS, you don't need to worry about what's in your option tag. Let AngularJS handle that; you should only care about what's in your model in your scope.
Here is a plunker demonstrating the behavior above, and showing the HTML written out个
处理默认选项:
关于缺省选项,有几件事我在上面没有提到.
Selecting the first option and removing the empty option:
您可以通过向ng-options
中重复的项目中的第一个元素添加一个简单的ng-init
来设置模型(从ng-model
开始)来实现此目的:
<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>
注意:如果foo
恰好被正确初始化为"falsy",这可能会有点疯狂.在这种情况下,很可能需要在控制器中处理foo
的初始化.
Customizing the default option:
这有点不同;这里您需要做的就是添加一个选项标记作为SELECT的子项,该标记具有空值属性,然后定制其内部文本:
<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="">Nothing selected</option>
</select>
注意:在这种情况下,即使 Select 了其他选项,"empty"选项仍将保留.AngularJS下的selects的默认行为并非如此.
A customized default option that hides after a selection is made:个
如果希望自定义默认选项在 Select 值后消失,可以向默认选项添加ng hide属性:
<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="" ng-if="foo">Select something to remove me.</option>
</select>