我试图使用一组对象
(array = [{name: 'Moe', id:1}, {name: 'Larry', id:2}, {name: 'Curly', id:3}])
Run Code Online (Sandbox Code Playgroud)
作为AngularJS输入表单中的下拉选择,我需要一个例子.任何人都可以指向一个可以启发我的jsFiddle吗?
Ben*_*esh 87
我建议你尽可能使用ng-options.
<select ng-model="choice" ng-options="x.id as x.name for x in array"></select>
Run Code Online (Sandbox Code Playgroud)
因为检查一下:你可以用它来选择实际的对象:
app.controller('ExampleCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'Foo' },
{ id: 2, name: 'Bar' }
];
$scope.selectedItem = null;
});
Run Code Online (Sandbox Code Playgroud)
<div ng-controller="ExampleCtrl">
<select ng-model="selectedItem"
ng-options="item as item.name for item in items"></select>
{{selectedItem | json}}
</div>
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,当您从下拉列表中选择某些内容时,它实际上是在selectedItem上设置整个对象引用,而不仅仅是值类型.
注意:使用ng-options将value=""
属性设置为集合中项目的索引,这是设计的.
这真的是最好的方法.
编辑:根据要求提供更多上下文.这里还有一个使用它的plunker
Gal*_*aim 21
<select ng-model="choice">
<option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)
或使用'ng-options' - http://docs.angularjs.org/api/ng.directive:select