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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:20:59  来源:igfitidea点击:

Angular js select binding

javascriptangularjs

提问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/selecthttp: //jsfiddle.net/qWzTb/,http : //jsfiddle.net/qm7E7/19/, Angular: Binding objects to <select>, ...以及其他一些堆栈溢出问题。

回答by David East

This is a tricky one. The ng-modeldirective 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>

http://jsfiddle.net/Fc5ne/4/

http://jsfiddle.net/Fc5ne/4/

回答by Razan Paul

For setting up the optionsof the select element, one can use ng-optionsdirective. For the selected value, one can use ng-modeldirective.

要设置select 元素的选项,可以使用ng-options指令。对于选定的值,可以使用ng-model指令。

jsfiddle: http://jsfiddle.net/rpaul/j5ewuek5/

jsfiddle:http: //jsfiddle.net/rpaul/j5ewuek5/