在AngularJS中绑定复选框或多选下拉列表

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

本文关键字:下拉列表 复选框 AngularJS 绑定      更新时间:2023-09-26

我是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'];

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

如果我做对了你想要的:

  1. 您没有ng-app定义。
  2. 在jsFiddle的AngularJS片段设置No wrap - in <head>加载模式,如果你使用AngularJS作为外部资源。
  3. 模型selected有它自己的"范围",因为你使用ng-repeat。为了明白我的意思,这里是你的代码的固定版本:http://jsfiddle.net/gBcN2/2/

第一个{{selected}}工作良好,但第二个是"超出"ng-repeat范围。

PS:


你不需要使用ng-repeat,如果你想使用它,就像你在你的例子中写的:快速摆弄我怎么做。

编辑:


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