javascript Angular js 选择绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24791408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular js select binding
提问by peinearydevelopment
I have looked at so many examples as to how to do this, but still can't seem to figure it out. I have setup a very simple angular app with controller and am trying to populate a single select tag.
我已经看过很多关于如何做到这一点的例子,但似乎仍然无法弄清楚。我已经设置了一个非常简单的带有控制器的 angular 应用程序,并且正在尝试填充单个选择标签。
<body data-ng-app="App">
<div data-ng-controller="DemoController">
{{var}}
<select data-ng-options="v.id as v.name for v in selectVals">
<option value="">Select</option>
</select>
</div>
</body>
angular.module('App', []).controller('DemoController', function($scope) {
$scope.var = 'a';
$scope.selectVals = [
{ name: '1st', id: 1 },
{ name: '2nd', id: 2 }
];
});
Here is the jsFiddle: http://jsfiddle.net/Fc5ne/3/Any help would be greatly appreciated.
这是 jsFiddle:http: //jsfiddle.net/Fc5ne/3/任何帮助将不胜感激。
I already looked in these places and tried to compare my code, but am still missing something: https://docs.angularjs.org/api/ng/directive/select, http://jsfiddle.net/qWzTb/, http://jsfiddle.net/qm7E7/19/, Angular: Binding objects to <select>, ... as well as a few other stack overflow questions.
我已经查看了这些地方并尝试比较我的代码,但仍然缺少一些东西:https: //docs.angularjs.org/api/ng/directive/select,http: //jsfiddle.net/qWzTb/,http : //jsfiddle.net/qm7E7/19/, Angular: Binding objects to <select>, ...以及其他一些堆栈溢出问题。
回答by David East
This is a tricky one. The ng-model
directive is required as well. Rest assured that many other people (including myself) have been burnt by this.
这是一个棘手的问题。该ng-model
指令也是必需的。请放心,许多其他人(包括我自己)都被这件事烧伤了。
<select data-ng-model="test" data-ng-options="v as v.name for v in selectVals"></select>
回答by Razan Paul
For setting up the optionsof the select element, one can use ng-options
directive.
For the selected value, one can use ng-model
directive.
要设置select 元素的选项,可以使用ng-options
指令。对于选定的值,可以使用ng-model
指令。
jsfiddle: http://jsfiddle.net/rpaul/j5ewuek5/
jsfiddle:http: //jsfiddle.net/rpaul/j5ewuek5/