javascript 将复选框或多选下拉列表绑定到 AngularJS 中的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16645153/
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-27 05:29:27  来源:igfitidea点击:

Bind checkbox or multi-select dropdown to array in AngularJS?

javascriptdata-bindingangularjshtml-selecthtml.checkbox

提问by Foo Stack

I am new to AngularJS, and am thus confused as how to bind checkboxes or multi-select dropdowns to a separate list.

我是 AngularJS 的新手,因此对如何将复选框或多选下拉列表绑定到单独的列表感到困惑。

<body ng-controller="FooListCtrl">
  <span ng-repeat="foolist in foos">
    <select ng-model="selected" ng-options="foo for foo in foolist" multiple="">
    </select>
  </span>
</body>
'use strict';

function FooListCtrl($scope) {
    $scope.foos = {"Bar": [ "foo", "bar"]};
    $scope.selected = [];
}

FooListCtrl.$inject = ['$scope'];

Run the code: http://jsfiddle.net/gBcN2/

运行代码:http: //jsfiddle.net/gBcN2/

采纳答案by the-lay

If I got right what you want:

如果我做对了你想要的:

  1. You don't have ng-appdefinition.
  2. On jsFiddle for snippets of AngularJS put No wrap - in <head>load mode, if you are using AngularJS as external resource.
  3. Model selectedhas it's own "range", because you use ng-repeat. To see what I mean, here is fixed version of your code: http://jsfiddle.net/gBcN2/2/
  1. 你没有ng-app定义。
  2. No wrap - in <head>如果您使用 AngularJS 作为外部资源,则在 jsFiddle 的 AngularJS 片段中设置加载模式。
  3. 模型selected有它自己的“范围”,因为您使用ng-repeat. 要明白我的意思,这里是你的代码的固定版本:http: //jsfiddle.net/gBcN2/2/

First {{selected}}works fine, but second is "outside" of ng-repeatscope.

第一个{{selected}}工作正常,但第二个是“超出”ng-repeat范围。

PS:
You don't have to use ng-repeatif you want to use it like you wrote in your example: quick fiddle of how I'd do it.

PS:如果你想像你在你的例子中写的那样使用它,
你不必ng-repeat使用它:我会如何做的快速小提琴。

Edit:
For checkboxes it's something like that - http://jsfiddle.net/qQg8u/2/

编辑:
对于复选框,它是这样的 - http://jsfiddle.net/qQg8u/2/