【问题标题】:How do I bind to list of checkbox values with AngularJS?如何使用 AngularJS 绑定到复选框值列表?
【发布时间】:2026-02-13 13:50:01
【问题描述】:

我有几个复选框:

<input type='checkbox' value="apple" checked>
<input type='checkbox' value="orange">
<input type='checkbox' value="pear" checked>
<input type='checkbox' value="naartjie">

我想绑定到我的控制器中的一个列表,这样每当一个复选框被更改时,控制器都会维护一个包含所有选中值的列表,例如,['apple', 'pear']

ng-model 似乎只能将单个复选框的值绑定到控制器中的变量。

还有其他方法可以将四个复选框绑定到控制器中的列表吗?

【问题讨论】:

  • 必须是列表吗?对象会起作用吗?:&lt;input type='checkbox' ng-model="checkboxes.apple"&gt; 等。模型将是:{"apple":true,"orange":false,"pear":true,"naartjie":true}
  • 试试这个Repo中的指令
  • 请务必查看已接受的答案。 another answer 在我看来更优雅。
  • naartjie !?那只会让你离开boet! :D
  • @ppumkin hehe 刚看到这个。你是对的:D

标签: javascript angularjs


【解决方案1】:

有两种方法可以解决这个问题。使用简单数组或对象数组。每个解决方案都有其优点和缺点。您可以在下面找到每种情况下的一个。


以简单数组作为输入数据

HTML 可能如下所示:

<label ng-repeat="fruitName in fruits">
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruitName}}"
    ng-checked="selection.indexOf(fruitName) > -1"
    ng-click="toggleSelection(fruitName)"
  > {{fruitName}}
</label>

适当的控制器代码是:

app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {

  // Fruits
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];

  // Selected fruits
  $scope.selection = ['apple', 'pear'];

  // Toggle selection for a given fruit by name
  $scope.toggleSelection = function toggleSelection(fruitName) {
    var idx = $scope.selection.indexOf(fruitName);

    // Is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // Is newly selected
    else {
      $scope.selection.push(fruitName);
    }
  };
}]);

优点:简单的数据结构和按名称切换很容易处理

缺点:添加/删除很麻烦,因为必须管理两个列表(输入和选择)


以对象数组作为输入数据

HTML 可能如下所示:

<label ng-repeat="fruit in fruits">
  <!--
    - Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
      traditionally

    - Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
      (no two-way-data-binding)

    - Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
      is arbitrary. The property name could be anything and will be created on the object if not present.
  -->
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruit.name}}"
    ng-model="fruit.selected"
  > {{fruit.name}}
</label>

适当的控制器代码是:

app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {

  // Fruits
  $scope.fruits = [
    { name: 'apple',    selected: true },
    { name: 'orange',   selected: false },
    { name: 'pear',     selected: true },
    { name: 'naartjie', selected: false }
  ];

  // Selected fruits
  $scope.selection = [];

  // Helper method to get selected fruits
  $scope.selectedFruits = function selectedFruits() {
    return filterFilter($scope.fruits, { selected: true });
  };

  // Watch fruits for changes
  $scope.$watch('fruits|filter:{selected:true}', function (nv) {
    $scope.selection = nv.map(function (fruit) {
      return fruit.name;
    });
  }, true);
}]);

优点:添加/删除非常简单

缺点:更复杂的数据结构和按名称切换很麻烦或需要辅助方法


演示http://jsbin.com/ImAqUC/1/

【讨论】:

  • 仅供参考,您可以注入filterFilter,而不是注入$filter,然后按如下方式使用: return filterFilter($scope.fruits, {checked: true});内置和自定义过滤器在 $injector 中注册,名称为 filterNameFilter(“filterName”应为斜体) -- $filterProvider docs
  • value="{{fruit.name}}"ng-checked="fruit.checked" 是多余的,因为使用了 ng-model。
  • 我注意到模型中不需要指定“checked”,Angular会自动设置属性:)
  • 应该使用 ng-change 而不是 ng-click,因为它可以更好地处理边缘情况。
  • @ViktorMolokostov 如果您要以传统方式提交表单,那将很有用。意味着将其发布到操作处理程序(一些服务器端脚本)。使用 php,具有类似名称的表单元素(使用方括号)在请求数据中创建一个数组。这样您就可以轻松处理选定的水果。
【解决方案2】:

一个简单的解决方案:

<div ng-controller="MainCtrl">
  <label ng-repeat="(color,enabled) in colors">
      <input type="checkbox" ng-model="colors[color]" /> {{color}} 
  </label>
  <p>colors: {{colors}}</p>
</div>

<script>
  var app = angular.module('plunker', []);

  app.controller('MainCtrl', function($scope){
      $scope.colors = {Blue: true, Orange: true};
  });
</script>

http://plnkr.co/edit/U4VD61?p=preview

【讨论】:

  • @kolypto - 这绝对是答案。我为使用对象的人(比如我)重写了它:plnkr.co/edit/cqsADe8lKegsBMgWMyB8?p=preview
  • 我和你一样,但是(color,enabled) in colors中的启用是做什么的?
  • @Sebastian,因为colors 是一个对象,所以当你迭代它时——你会得到一对(key,value)
  • 虽然我非常喜欢这个答案!我认为,使用对象作为数据源存在一个主要问题。也就是说,根据定义,对象属性的顺序是未定义的,因此在显示复选框时无法提供明确的顺序。还是 +1 ;)
  • colors 应该命名为isSelectedisSelected[color]colors[color] 更容易阅读
【解决方案3】:
<input type='checkbox' ng-repeat="fruit in fruits"
  ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)">

.

function SomeCtrl ($scope) {
    $scope.fruits = ["apple, orange, pear, naartjie"];
    $scope.checkedFruits = [];
    $scope.toggleCheck = function (fruit) {
        if ($scope.checkedFruits.indexOf(fruit) === -1) {
            $scope.checkedFruits.push(fruit);
        } else {
            $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1);
        }
    };
}

【讨论】:

  • 爱这多么简单,正是我正在寻找的(尽管我不得不承认@vitalets 指令是惊人的)。我稍微修改了 Umur 的代码来创建这个小提琴:jsfiddle.net/samurai_jane/9mwsbfuc
  • 我把武士简的话变成我的!展示我需要的东西是多么简单! :)
【解决方案4】:

这是一个快速的、可重复使用的小指令,似乎可以完成您想要做的事情。我简单地称它为checkList。它在复选框更改时更新数组,并在数组更改时更新复选框。

app.directive('checkList', function() {
  return {
    scope: {
      list: '=checkList',
      value: '@'
    },
    link: function(scope, elem, attrs) {
      var handler = function(setup) {
        var checked = elem.prop('checked');
        var index = scope.list.indexOf(scope.value);

        if (checked && index == -1) {
          if (setup) elem.prop('checked', false);
          else scope.list.push(scope.value);
        } else if (!checked && index != -1) {
          if (setup) elem.prop('checked', true);
          else scope.list.splice(index, 1);
        }
      };

      var setupHandler = handler.bind(null, true);
      var changeHandler = handler.bind(null, false);

      elem.bind('change', function() {
        scope.$apply(changeHandler);
      });
      scope.$watch('list', setupHandler, true);
    }
  };
});

这里有一个控制器和一个视图,显示了您可以如何使用它。

<div ng-app="myApp" ng-controller='MainController'>
  <span ng-repeat="fruit in fruits">
    <input type='checkbox' value="{{fruit}}" check-list='checked_fruits'> {{fruit}}<br />
  </span>

  <div>The following fruits are checked: {{checked_fruits | json}}</div>

  <div>Add fruit to the array manually:
    <button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'>{{fruit}}</button>
  </div>
</div>
app.controller('MainController', function($scope) {
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
  $scope.checked_fruits = ['apple', 'pear'];
  $scope.addFruit = function(fruit) {
    if ($scope.checked_fruits.indexOf(fruit) != -1) return;
    $scope.checked_fruits.push(fruit);
  };
});

(按钮表明更改数组也会更新复选框。)

最后,下面是 Plunker 上的指令示例:http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview

【讨论】:

  • 谢谢布兰登,这正是我想要的(也正是问题所要求的,与其他答案不同)。我所做的唯一调整是将您的 "elem.on('change', function() ..." 更改为 "elem.bind('change', function()..." 以消除对 jQuery 的依赖.
  • 这很简洁,但不知何故破坏了我使用 ng-disabled 的能力 :( 有什么办法可以解决这个问题吗?
  • 超级好用!甚至为我使用对象而不是源列表和数据列表的数组!
  • 我同意大家的看法。这是最有用的,无疑是可重复使用的!!感谢您的出色工作。 :)
  • 如果您在使用 AngularJS >= 1.4.4 时遇到问题,请检查 github.com/angular/angular.js/issues/13037:将 value: '@' 替换为 value: '=ngValue'
【解决方案5】:

根据此线程中的答案,我创建了涵盖所有情况的 checklist-model 指令:

  • 简单的基元数组
  • 对象数组(选择 id 或整个对象)
  • 对象属性迭代

对于主题启动案例,它将是:

<label ng-repeat="fruit in ['apple', 'orange', 'pear', 'naartjie']">
    <input type="checkbox" checklist-model="selectedFruits" checklist-value="fruit"> {{fruit}}
</label>

【讨论】:

  • 这看起来像我需要的。在异步获取数据时,您是否有机会解释如何使用它?那部分让我很困惑。
  • 异步获取数据后,只需修改作用域中的 checlist 模型,在上面的示例中为selectedFruits
【解决方案6】:

使用$index 的字符串可以帮助使用选定值的哈希图:

<ul>
    <li ng-repeat="someItem in someArray">
        <input type="checkbox" ng-model="someObject[$index.toString()]" />
    </li>
</ul>

这样,ng-model 对象将使用代表索引的键进行更新。

$scope.someObject = {};

一段时间后$scope.someObject 应该看起来像:

$scope.someObject = {
     0: true,
     4: false,
     1: true
};

此方法不适用于所有情况,但很容易实现。

【讨论】:

  • 这是一个非常优雅的解决方案,适合我的情况(使用 AJAX)
  • 使用接吻法
【解决方案7】:

由于您接受了未使用列表的答案,我假设我的评论问题的答案是“不,它不必是列表”。我还觉得您可能正在渲染 HTML 服务器端,因为您的示例 HTML 中存在“已选中”(如果使用 ng-model 为您的复选框建模,则不需要这样做)。

无论如何,当我问这个问题时,这就是我的想法,同时假设您正在生成 HTML 服务器端:

<div ng-controller="MyCtrl" 
 ng-init="checkboxes = {apple: true, orange: false, pear: true, naartjie: false}">
    <input type="checkbox" ng-model="checkboxes.apple">apple
    <input type="checkbox" ng-model="checkboxes.orange">orange
    <input type="checkbox" ng-model="checkboxes.pear">pear
    <input type="checkbox" ng-model="checkboxes.naartjie">naartjie
    <br>{{checkboxes}}
</div>

ng-init 允许服务器端生成的 HTML 初始设置某些复选框。

Fiddle.

【讨论】:

    【解决方案8】:

    我认为最简单的解决方法是使用“select”并指定“multiple”:

    <select ng-model="selectedfruit" multiple ng-options="v for v in fruit"></select>
    

    否则,我认为您必须处理列表才能构建列表 (通过$watch()ing 模型数组绑定复选框)。

    【讨论】:

    • 他要求一个复选框列表,而您却告诉他有关带选项的选择。这是完全不同的。
    • @CrazySabbath:但您不理解他提出了替代解决方案,而这个答案作为“替代解决方案”帮助了其他 6 人
    【解决方案9】:

    以下解决方案似乎是一个不错的选择,

    <label ng-repeat="fruit in fruits">
      <input
        type="checkbox"
        ng-model="fruit.checked"
        ng-value="true"
      > {{fruit.fruitName}}
    </label>
    

    并且在控制器型号中fruits 会是这样的

    $scope.fruits = [
      {
        "name": "apple",
        "checked": true
      },
      {
        "name": "orange"
      },
      {
        "name": "grapes",
        "checked": true
      }
    ];
    

    【讨论】:

    • 我看这些例子的次数越多,似乎我就必须将我的数组映射到一个对象数组中。
    【解决方案10】:

    我已经修改了 Yoshi 接受的答案来处理复杂的对象(而不是字符串)。

    HTML

    <div ng-controller="TestController">
        <p ng-repeat="permission in allPermissions">
            <input type="checkbox" ng-checked="selectedPermissions.containsObjectWithProperty('id', permission.id)" ng-click="toggleSelection(permission)" />
            {{permission.name}}
        </p>
    
        <hr />
    
        <p>allPermissions: | <span ng-repeat="permission in allPermissions">{{permission.name}} | </span></p>
        <p>selectedPermissions: | <span ng-repeat="permission in selectedPermissions">{{permission.name}} | </span></p>
    </div>
    

    JavaScript

    Array.prototype.indexOfObjectWithProperty = function(propertyName, propertyValue)
    {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i][propertyName] === propertyValue) return i;
        }
    
        return -1;
    };
    
    
    Array.prototype.containsObjectWithProperty = function(propertyName, propertyValue)
    {
        return this.indexOfObjectWithProperty(propertyName, propertyValue) != -1;
    };
    
    
    function TestController($scope)
    {
        $scope.allPermissions = [
        { "id" : 1, "name" : "ROLE_USER" },
        { "id" : 2, "name" : "ROLE_ADMIN" },
        { "id" : 3, "name" : "ROLE_READ" },
        { "id" : 4, "name" : "ROLE_WRITE" } ];
    
        $scope.selectedPermissions = [
        { "id" : 1, "name" : "ROLE_USER" },
        { "id" : 3, "name" : "ROLE_READ" } ];
    
        $scope.toggleSelection = function toggleSelection(permission) {
            var index = $scope.selectedPermissions.indexOfObjectWithProperty('id', permission.id);
    
            if (index > -1) {
                $scope.selectedPermissions.splice(index, 1);
            } else {
                $scope.selectedPermissions.push(permission);
            }
        };
    }
    

    工作示例:http://jsfiddle.net/tCU8v/

    【讨论】:

    • 你不应该有一个没有包装或匹配&lt;label&gt;&lt;input type="checkbox"&gt;!现在你的用户必须点击实际的复选框而不是复选框旁边的文本,这更加困难并且可用性差。
    【解决方案11】:

    另一个简单的指令可能是:

    var appModule = angular.module("appModule", []);
    
    appModule.directive("checkList", [function () {
    return {
        restrict: "A",
        scope: {
            selectedItemsArray: "=",
            value: "@"
        },
        link: function (scope, elem) {
            scope.$watchCollection("selectedItemsArray", function (newValue) {
                if (_.contains(newValue, scope.value)) {
                    elem.prop("checked", true);
                } else {
                    elem.prop("checked", false);
                }
            });
            if (_.contains(scope.selectedItemsArray, scope.value)) {
                elem.prop("checked", true);
            }
            elem.on("change", function () {
                if (elem.prop("checked")) {
                    if (!_.contains(scope.selectedItemsArray, scope.value)) {
                        scope.$apply(
                            function () {
                                scope.selectedItemsArray.push(scope.value);
                            }
                        );
                    }
                } else {
                    if (_.contains(scope.selectedItemsArray, scope.value)) {
                        var index = scope.selectedItemsArray.indexOf(scope.value);
                        scope.$apply(
                            function () {
                                scope.selectedItemsArray.splice(index, 1);
                            });
                    }
                }
                console.log(scope.selectedItemsArray);
            });
        }
    };
    }]);
    

    控制器:

    appModule.controller("sampleController", ["$scope",
      function ($scope) {
        //#region "Scope Members"
        $scope.sourceArray = [{ id: 1, text: "val1" }, { id: 2, text: "val2" }];
        $scope.selectedItems = ["1"];
        //#endregion
        $scope.selectAll = function () {
          $scope.selectedItems = ["1", "2"];
      };
        $scope.unCheckAll = function () {
          $scope.selectedItems = [];
        };
    }]);
    

    还有 HTML:

    <ul class="list-unstyled filter-list">
    <li data-ng-repeat="item in sourceArray">
        <div class="checkbox">
            <label>
                <input type="checkbox" check-list selected-items-array="selectedItems" value="{{item.id}}">
                {{item.text}}
            </label>
        </div>
    </li>
    

    我还包括一个 Plunker:http://plnkr.co/edit/XnFtyij4ed6RyFwnFN6V?p=preview

    【讨论】:

      【解决方案12】:

      您不必编写所有代码。 AngularJS 将通过使用 ngTrueValue 和 ngFalseValue 使模型和复选框保持同步

      在这里编写代码:http://codepen.io/paulbhartzog/pen/kBhzn

      代码sn-p:

      <p ng-repeat="item in list1" class="item" id="{{item.id}}">
        <strong>{{item.id}}</strong> <input name='obj1_data' type="checkbox" ng-model="list1[$index].data" ng-true-value="1" ng-false-value="0"> Click this to change data value below
      </p>
      <pre>{{list1 | json}}</pre>
      

      【讨论】:

      • 这不是 OP 的要求。
      • 将复选框绑定到列表是被要求的,也是我所做的。可以修改阵列以适应应用程序。关键是复选框是绑定的。 ngTrueValue 和 ngFalseValue 也可用于映射到仅列出其他属性(例如名称)的第二个数组。
      • OP 想要一个检查值的列表,而不是所有值的列表,检查和未检查。
      【解决方案13】:

      查看这个有效管理复选框列表的指令。我希望这个对你有用。 CheckList Model

      【讨论】:

        【解决方案14】:

        有一种方法可以通过ng-model-options="{ getterSetter: true }"直接处理数组并同时使用ng-model。

        诀窍是在您的 ng-model 中使用 getter/setter 函数。这样你就可以使用一个数组作为你的真实模型并“伪造”输入模型中的布尔值:

        <label ng-repeat="fruitName in ['apple', 'orange', 'pear', 'naartjie']">
          <input
            type="checkbox"
            ng-model="fruitsGetterSetterGenerator(fruitName)"
            ng-model-options="{ getterSetter: true }"
          > {{fruitName}}
        </label>
        

        $scope.fruits = ['apple', 'pear']; // pre checked
        
        $scope.fruitsGetterSetterGenerator = function(fruitName){
            return function myGetterSetter(nowHasFruit){
                if (nowHasFruit !== undefined){
        
                    // Setter
                    fruitIndex = $scope.fruits.indexOf(fruit);
                    didHaveFruit = (fruitIndex !== -1);
                    mustAdd = (!didHaveFruit && nowHasFruit);
                    mustDel = (didHaveFruit && !nowHasFruit);
                    if (mustAdd){
                        $scope.fruits.push(fruit);
                    }
                    if (mustDel){
                        $scope.fruits.splice(fruitIndex, 1);
                    }
                }
                else {
                    // Getter
                    return $scope.user.fruits.indexOf(fruit) !== -1;
                }
            }
        }
        

        CAVEAT 如果您的数组很大,则不应使用此方法,因为myGetterSetter 会被多次调用。

        有关更多信息,请参阅https://docs.angularjs.org/api/ng/directive/ngModelOptions

        【讨论】:

          【解决方案15】:

          我喜欢 Yoshi 的回答。我对其进行了增强,因此您可以对多个列表使用相同的功能。

          <label ng-repeat="fruitName in fruits">
          <input
          type="checkbox"
          name="selectedFruits[]"
          value="{{fruitName}}"
          ng-checked="selection.indexOf(fruitName) > -1"
          ng-click="toggleSelection(fruitName, selection)"> {{fruitName}}
          </label>
          
          
          <label ng-repeat="veggieName in veggies">
          <input
          type="checkbox"
          name="selectedVeggies[]"
          value="{{veggieName}}"
          ng-checked="veggieSelection.indexOf(veggieName) > -1"
          ng-click="toggleSelection(veggieName, veggieSelection)"> {{veggieName}}
          </label>
          
          
          
          app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
            // fruits
            $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
            $scope.veggies = ['lettuce', 'cabbage', 'tomato']
            // selected fruits
            $scope.selection = ['apple', 'pear'];
            $scope.veggieSelection = ['lettuce']
            // toggle selection for a given fruit by name
            $scope.toggleSelection = function toggleSelection(selectionName, listSelection) {
              var idx = listSelection.indexOf(selectionName);
          
              // is currently selected
              if (idx > -1) {
                listSelection.splice(idx, 1);
              }
          
              // is newly selected
              else {
                listSelection.push(selectionName);
              }
            };
          }]);
          

          http://plnkr.co/edit/KcbtzEyNMA8s1X7Hja8p?p=preview

          【讨论】:

            【解决方案16】:

            如果您在同一个表单上有多个复选框

            控制器代码

            vm.doYouHaveCheckBox = ['aaa', 'ccc', 'bbb'];
            vm.desiredRoutesCheckBox = ['ddd', 'ccc', 'Default'];
            vm.doYouHaveCBSelection = [];
            vm.desiredRoutesCBSelection = [];
            

            查看代码

            <div ng-repeat="doYouHaveOption in vm.doYouHaveCheckBox">
                <div class="action-checkbox">
                    <input id="{{doYouHaveOption}}" type="checkbox" value="{{doYouHaveOption}}" ng-checked="vm.doYouHaveCBSelection.indexOf(doYouHaveOption) > -1" ng-click="vm.toggleSelection(doYouHaveOption,vm.doYouHaveCBSelection)" />
                    <label for="{{doYouHaveOption}}"></label>
                    {{doYouHaveOption}}
                </div>
            </div>
            
            <div ng-repeat="desiredRoutesOption in vm.desiredRoutesCheckBox">
                 <div class="action-checkbox">
                      <input id="{{desiredRoutesOption}}" type="checkbox" value="{{desiredRoutesOption}}" ng-checked="vm.desiredRoutesCBSelection.indexOf(desiredRoutesOption) > -1" ng-click="vm.toggleSelection(desiredRoutesOption,vm.desiredRoutesCBSelection)" />
                      <label for="{{desiredRoutesOption}}"></label>
                      {{desiredRoutesOption}}
                 </div>
            </div>        
            

            【讨论】:

              【解决方案17】:

              灵感来自上面 Yoshi 的帖子。 这是plnkr

              (function () {
                 
                 angular
                    .module("APP", [])
                    .controller("demoCtrl", ["$scope", function ($scope) {
                       var dc = this
                       
                       dc.list = [
                          "Selection1",
                          "Selection2",
                          "Selection3"
                       ]
              
                       dc.multipleSelections = []
                       dc.individualSelections = []
                       
                       // Using splice and push methods to make use of 
                       // the same "selections" object passed by reference to the 
                       // addOrRemove function as using "selections = []" 
                       // creates a new object within the scope of the 
                       // function which doesn't help in two way binding.
                       dc.addOrRemove = function (selectedItems, item, isMultiple) {
                          var itemIndex = selectedItems.indexOf(item)
                          var isPresent = (itemIndex > -1)
                          if (isMultiple) {
                             if (isPresent) {
                                selectedItems.splice(itemIndex, 1)
                             } else {
                                selectedItems.push(item)
                             }
                          } else {
                             if (isPresent) {
                                selectedItems.splice(0, 1)
                             } else {
                                selectedItems.splice(0, 1, item)
                             }
                          }
                       }
                       
                    }])
                 
              })()
              label {
                display: block;  
              }
              <!DOCTYPE html>
              <html>
              
                 <head>
                    <link rel="stylesheet" href="style.css" />
                 </head>
              
                 <body ng-app="APP" ng-controller="demoCtrl as dc">
                    <h1>checkbox-select demo</h1>
                    
                    <h4>Multiple Selections</h4>
                    <label ng-repeat="thing in dc.list">
                       <input 
                          type="checkbox" 
                          ng-checked="dc.multipleSelections.indexOf(thing) > -1"
                          ng-click="dc.addOrRemove(dc.multipleSelections, thing, true)"
                       > {{thing}}
                    </label>
                    
                    <p>
                       dc.multipleSelections :- {{dc.multipleSelections}}
                    </p>
                    
                    <hr>
                    
                    <h4>Individual Selections</h4>
                    <label ng-repeat="thing in dc.list">
                       <input 
                          type="checkbox" 
                          ng-checked="dc.individualSelections.indexOf(thing) > -1"
                          ng-click="dc.addOrRemove(dc.individualSelections, thing, false)"
                       > {{thing}}
                    </label>
                    
                    <p>
                       dc.invidualSelections :- {{dc.individualSelections}}
                    </p>
                    
                    <script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
                    <script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
                    <script src="script.js"></script>
                 </body>
              
              </html>

              【讨论】:

                【解决方案18】:

                根据我的另一篇帖子here,我做了一个可重复使用的指令。

                查看GitHub repository

                (function () {
                   
                   angular
                      .module("checkbox-select", [])
                      .directive("checkboxModel", ["$compile", function ($compile) {
                         return {
                            restrict: "A",
                            link: function (scope, ele, attrs) {
                               // Defining updateSelection function on the parent scope
                               if (!scope.$parent.updateSelections) {
                                  // Using splice and push methods to make use of 
                                  // the same "selections" object passed by reference to the 
                                  // addOrRemove function as using "selections = []" 
                                  // creates a new object within the scope of the 
                                  // function which doesn't help in two way binding.
                                  scope.$parent.updateSelections = function (selectedItems, item, isMultiple) {
                                     var itemIndex = selectedItems.indexOf(item)
                                     var isPresent = (itemIndex > -1)
                                     if (isMultiple) {
                                        if (isPresent) {
                                           selectedItems.splice(itemIndex, 1)
                                        } else {
                                           selectedItems.push(item)
                                        }
                                     } else {
                                        if (isPresent) {
                                           selectedItems.splice(0, 1)
                                        } else {
                                           selectedItems.splice(0, 1, item)
                                        }
                                     }
                                  }   
                               }
                               
                               // Adding or removing attributes
                               ele.attr("ng-checked", attrs.checkboxModel + ".indexOf(" + attrs.checkboxValue + ") > -1")
                               var multiple = attrs.multiple ? "true" : "false"
                               ele.attr("ng-click", "updateSelections(" + [attrs.checkboxModel, attrs.checkboxValue, multiple].join(",") + ")")
                               
                               // Removing the checkbox-model attribute, 
                               // it will avoid recompiling the element infinitly
                               ele.removeAttr("checkbox-model")
                               ele.removeAttr("checkbox-value")
                               ele.removeAttr("multiple")
                               
                               $compile(ele)(scope)
                            }
                         }
                      }])
                   
                      // Defining app and controller
                      angular
                      .module("APP", ["checkbox-select"])
                      .controller("demoCtrl", ["$scope", function ($scope) {
                         var dc = this
                         dc.list = [
                            "selection1",
                            "selection2",
                            "selection3"
                         ]
                         
                         // Define the selections containers here
                         dc.multipleSelections = []
                         dc.individualSelections = []
                      }])
                   
                })()
                label {
                  display: block;  
                }
                <!DOCTYPE html>
                <html>
                
                   <head>
                      <link rel="stylesheet" href="style.css" />
                      
                   </head>
                   
                   <body ng-app="APP" ng-controller="demoCtrl as dc">
                      <h1>checkbox-select demo</h1>
                      
                      <h4>Multiple Selections</h4>
                      <label ng-repeat="thing in dc.list">
                         <input type="checkbox" checkbox-model="dc.multipleSelections" checkbox-value="thing" multiple>
                         {{thing}}
                      </label>
                      <p>dc.multipleSelecitons:- {{dc.multipleSelections}}</p>
                      
                      <h4>Individual Selections</h4>
                      <label ng-repeat="thing in dc.list">
                         <input type="checkbox" checkbox-model="dc.individualSelections" checkbox-value="thing">
                         {{thing}}
                      </label>
                      <p>dc.individualSelecitons:- {{dc.individualSelections}}</p>
                      
                      <script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
                      <script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
                      <script src="script.js"></script>
                   </body>
                
                </html>

                【讨论】:

                  【解决方案19】:

                  在 HTML 中(假设复选框位于表格中每一行的第一列)。

                  <tr ng-repeat="item in fruits">
                      <td><input type="checkbox" ng-model="item.checked" ng-click="getChecked(item)"></td>
                      <td ng-bind="fruit.name"></td>
                      <td ng-bind="fruit.color"></td>
                      ...
                  </tr>
                  

                  controllers.js 文件中:

                  // The data initialization part...
                  $scope.fruits = [
                      {
                        name: ....,
                        color:....
                      },
                      {
                        name: ....,
                        color:....
                      }
                       ...
                      ];
                  
                  // The checked or not data is stored in the object array elements themselves
                  $scope.fruits.forEach(function(item){
                      item.checked = false;
                  });
                  
                  // The array to store checked fruit items
                  $scope.checkedItems = [];
                  
                  // Every click on any checkbox will trigger the filter to find checked items
                  $scope.getChecked = function(item){
                      $scope.checkedItems = $filter("filter")($scope.fruits,{checked:true});
                  };
                  

                  【讨论】:

                    【解决方案20】:

                    这是另一种解决方案。我的解决方案的好处:

                    • 它不需要任何额外的手表(这可能会影响性能)
                    • 它不需要控制器中的任何代码保持干净
                    • 代码还是有点短
                    • 只需要很少的代码就可以在多个地方重用,因为它只是一个指令

                    指令如下:

                    function ensureArray(o) {
                        var lAngular = angular;
                        if (lAngular.isArray(o) || o === null || lAngular.isUndefined(o)) {
                            return o;
                        }
                        return [o];
                    }
                    
                    function checkboxArraySetDirective() {
                        return {
                            restrict: 'A',
                            require: 'ngModel',
                            link: function(scope, element, attrs, ngModel) {
                                var name = attrs.checkboxArraySet;
                    
                                ngModel.$formatters.push(function(value) {
                                    return (ensureArray(value) || []).indexOf(name) >= 0;
                                });
                    
                                ngModel.$parsers.push(function(value) {
                                    var modelValue = ensureArray(ngModel.$modelValue) || [],
                                        oldPos = modelValue.indexOf(name),
                                        wasSet = oldPos >= 0;
                                    if (value) {
                                        if (!wasSet) {
                                            modelValue = angular.copy(modelValue);
                                            modelValue.push(name);
                                        }
                                    } else if (wasSet) {
                                        modelValue = angular.copy(modelValue);
                                        modelValue.splice(oldPos, 1);
                                    }
                                    return modelValue;
                                });
                            }
                        }
                    }
                    

                    最后然后像这样使用它:

                    <input ng-repeat="fruit in ['apple', 'banana', '...']" type="checkbox" ng-model="fruits" checkbox-array-set="{{fruit}}" />
                    

                    这就是全部。唯一添加的是checkbox-array-set 属性。

                    【讨论】:

                      【解决方案21】:

                      您可以结合使用 AngularJS 和 jQuery。例如,您需要在控制器中定义一个数组$scope.selected = [];

                      <label ng-repeat="item in items">
                          <input type="checkbox" ng-model="selected[$index]" ng-true-value="'{{item}}'">{{item}}
                      </label>
                      

                      您可以获得一个拥有所选项目的数组。使用alert(JSON.stringify($scope.selected))方法,可以查看选中的项目。

                      【讨论】:

                      • 完美!...这是使用数组而不是对象的最简单解决方案
                      • 不要结合 Jquery 和 Angular
                      • 这将导致所选阵列出现空洞。检查这个post
                      【解决方案22】:
                        <div ng-app='app' >
                          <div ng-controller='MainCtrl' >
                             <ul> 
                             <li ng-repeat="tab in data">
                               <input type='checkbox' ng-click='change($index,confirm)' ng-model='confirm' />
                               {{tab.name}} 
                               </li>
                           </ul>
                          {{val}}
                         </div>
                       </div>
                      
                      
                      var app = angular.module('app', []);
                       app.controller('MainCtrl',function($scope){
                       $scope.val=[];
                        $scope.confirm=false;
                        $scope.data=[
                         {
                           name:'vijay'
                           },
                          {
                            name:'krishna'
                          },{
                            name:'Nikhil'
                           }
                          ];
                          $scope.temp;
                         $scope.change=function(index,confirm){
                           console.log(confirm);
                          if(!confirm){
                           ($scope.val).push($scope.data[index]);   
                          }
                          else{
                          $scope.temp=$scope.data[index];
                              var d=($scope.val).indexOf($scope.temp);
                              if(d!=undefined){
                               ($scope.val).splice(d,1);
                              }    
                             }
                           }   
                         })
                      

                      【讨论】:

                        【解决方案23】:

                        看看这个:checklist-model

                        它适用于 JavaScript 数组和对象,它可以使用静态 HTML 复选框,无需 ng-repeat

                        <label><input type="checkbox" checklist-model="roles" value="admin"> Administrator</label>
                        <label><input type="checkbox" checklist-model="roles" value="customer"> Customer</label>
                        <label><input type="checkbox" checklist-model="roles" value="guest"> Guest</label>
                        <label><input type="checkbox" checklist-model="roles" value="user"> User</label>
                        

                        还有 JavaScript 方面:

                        var app = angular.module("app", ["checklist-model"]);
                        app.controller('Ctrl4a', function($scope) {
                            $scope.roles = [];
                        });
                        

                        【讨论】:

                          【解决方案24】:

                          一个简单的 HTML 唯一方法:

                          <input type="checkbox"
                                 ng-checked="fruits.indexOf('apple') > -1"
                                 ng-click="fruits.indexOf('apple') > -1 ? fruits.splice(fruits.indexOf('apple'), 1) : fruits.push('apple')">
                          <input type="checkbox"
                                 ng-checked="fruits.indexOf('orange') > -1"
                                 ng-click="fruits.indexOf('orange') > -1 ? fruits.splice(fruits.indexOf('orange'), 1) : fruits.push('orange')">
                          <input type="checkbox"
                                 ng-checked="fruits.indexOf('pear') > -1"
                                 ng-click="fruits.indexOf('pear') > -1 ? fruits.splice(fruits.indexOf('pear'), 1) : fruits.push('pear')">
                          <input type="checkbox"
                                 ng-checked="fruits.indexOf('naartjie') > -1"
                                 ng-click="fruits.indexOf('apple') > -1 ? fruits.splice(fruits.indexOf('apple'), 1) : fruits.push('naartjie')">

                          【讨论】:

                            【解决方案25】:

                            使用@Umur Kontacı 的this example,我认为使用它来捕获另一个对象/数组中的选定数据,例如编辑页面。

                            在数据库中捕获选项

                            切换某个选项

                            例如,下面所有颜色的json:

                            {
                                "colors": [
                                    {
                                        "id": 1,
                                        "title": "Preto - #000000"
                                    },
                                    {
                                        "id": 2,
                                        "title": "Azul - #005AB1"
                                    },
                                    {
                                        "id": 3,
                                        "title": "Azul Marinho - #001A66"
                                    },
                                    {
                                        "id": 4,
                                        "title": "Amarelo - #FFF100"
                                    },
                                    {
                                        "id": 5,
                                        "title": "Vermelho - #E92717"
                                    },
                                    {
                                        "id": 6,
                                        "title": "Verde - #008D2F"
                                    },
                                    {
                                        "id": 7,
                                        "title": "Cinza - #8A8A8A"
                                    },
                                    {
                                        "id": 8,
                                        "title": "Prata - #C8C9CF"
                                    },
                                    {
                                        "id": 9,
                                        "title": "Rosa - #EF586B"
                                    },
                                    {
                                        "id": 10,
                                        "title": "Nude - #E4CAA6"
                                    },
                                    {
                                        "id": 11,
                                        "title": "Laranja - #F68700"
                                    },
                                    {
                                        "id": 12,
                                        "title": "Branco - #FFFFFF"
                                    },
                                    {
                                        "id": 13,
                                        "title": "Marrom - #764715"
                                    },
                                    {
                                        "id": 14,
                                        "title": "Dourado - #D9A300"
                                    },
                                    {
                                        "id": 15,
                                        "title": "Bordo - #57001B"
                                    },
                                    {
                                        "id": 16,
                                        "title": "Roxo - #3A0858"
                                    },
                                    {
                                        "id": 18,
                                        "title": "Estampado "
                                    },
                                    {
                                        "id": 17,
                                        "title": "Bege - #E5CC9D"
                                    }
                                ]
                            }
                            

                            还有两种数据对象,array 包含一个对象,object 包含两个/更多对象数据:

                            • 在数据库中捕获的两个项目:

                              [{"id":12,"title":"Branco - #FFFFFF"},{"id":16,"title":"Roxo - #3A0858"}]
                              
                            • 在数据库中选择的一个项目:

                              {"id":12,"title":"Branco - #FFFFFF"}
                              

                            在这里,我的 javascript 代码:

                            /**
                             * Add this code after catch data of database.
                             */
                            
                            vm.checkedColors = [];
                            var _colorObj = vm.formData.color_ids;
                            var _color_ids = [];
                            
                            if (angular.isObject(_colorObj)) {
                                // vm.checkedColors.push(_colorObj);
                                _color_ids.push(_colorObj);
                            } else if (angular.isArray(_colorObj)) {
                                angular.forEach(_colorObj, function (value, key) {
                                    // vm.checkedColors.push(key + ':' + value);
                                    _color_ids.push(key + ':' + value);
                                });
                            }
                            
                            angular.forEach(vm.productColors, function (object) {
                                angular.forEach(_color_ids, function (color) {
                                    if (color.id === object.id) {
                                        vm.checkedColors.push(object);
                                    }
                                });
                            });
                            
                            /**
                             * Add this code in your js function initialized in this HTML page
                             */
                            vm.toggleColor = function (color) {
                                console.log('toggleColor is: ', color);
                            
                                if (vm.checkedColors.indexOf(color) === -1) {
                                    vm.checkedColors.push(color);
                                } else {
                                    vm.checkedColors.splice(vm.checkedColors.indexOf(color), 1);
                                }
                                vm.formData.color_ids = vm.checkedColors;
                            };
                            

                            我的 HTML 代码:

                            <div class="checkbox" ng-repeat="color in productColors">
                                <label>
                                    <input type="checkbox"
                                           ng-checked="checkedColors.indexOf(color) != -1"
                                           ng-click="toggleColor(color)"/>
                                    <% color.title %>
                                </label>
                            </div>
                            
                            <p>checkedColors Output:</p>
                            <pre><% checkedColors %></pre>
                            

                            [编辑] 重构代码如下:

                            function makeCheckedOptions(objectOptions, optionObj) {
                                var checkedOptions = [];
                                var savedOptions = [];
                            
                                if (angular.isObject(optionObj)) {
                                    savedOptions.push(optionObj);
                                } else if (angular.isArray(optionObj)) {
                                    angular.forEach(optionObj, function (value, key) {
                                        savedOptions.push(key + ':' + value);
                                    });
                                }
                            
                                angular.forEach(objectOptions, function (object) {
                                    angular.forEach(savedOptions, function (color) {
                                        if (color.id === object.id) {
                                            checkedOptions.push(object);
                                        }
                                    });
                                });
                            
                                return checkedOptions;
                            }
                            

                            并调用新方法如下:

                            vm.checkedColors = makeCheckedOptions(productColors, vm.formData.color_ids);
                            

                            就是这样!

                            【讨论】:

                              【解决方案26】:

                              我在控制器中放了一个数组。

                              $scope.statuses = [{ name: 'Shutdown - Reassessment Required' },
                                  { name: 'Under Construction' },
                                  { name: 'Administrative Cancellation' },
                                  { name: 'Initial' },
                                  { name: 'Shutdown - Temporary' },
                                  { name: 'Decommissioned' },
                                  { name: 'Active' },
                                  { name: 'SO Shutdown' }]
                              

                              在标记上我放了如下内容

                              <div ng-repeat="status in $scope.statuses">
                                 <input type="checkbox" name="unit_status" ng-model="$scope.checkboxes[status.name]"> {{status.name}}
                                 <br>                        
                              </div>
                              {{$scope.checkboxes}}
                              

                              输出如下,在控制器中我只需要检查它的真假; true 为选中,缺席/false 为未选中。

                              {
                              "Administrative Cancellation":true,
                              "Under Construction":true,
                              "Shutdown - Reassessment Required":true,
                              "Decommissioned":true,
                              "Active":true
                              }
                              

                              希望这会有所帮助。

                              【讨论】:

                                【解决方案27】:

                                我认为以下方式对于嵌套的 ng-repeats 更加清晰和有用。查看Plunker

                                Quote from this thread:

                                <html ng-app="plunker">
                                    <head>
                                        <title>Test</title>
                                        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
                                    </head>
                                
                                    <body ng-controller="MainCtrl">
                                        <div ng-repeat="tab in mytabs">
                                
                                            <h1>{{tab.name}}</h1>
                                            <div ng-repeat="val in tab.values">
                                                <input type="checkbox" ng-change="checkValues()" ng-model="val.checked"/>
                                            </div>
                                        </div>
                                
                                        <br>
                                        <pre> {{selected}} </pre>
                                
                                            <script>
                                                var app = angular.module('plunker', []);
                                
                                                app.controller('MainCtrl', function ($scope,$filter) {
                                                    $scope.mytabs = [
                                             {
                                                 name: "tab1",
                                                 values: [
                                                     { value: "value1",checked:false },
                                                     { value: "value2", checked: false },
                                                     { value: "value3", checked: false },
                                                     { value: "value4", checked: false }
                                                 ]
                                             },
                                             {
                                                 name: "tab2",
                                                 values: [
                                                     { value: "value1", checked: false },
                                                     { value: "value2", checked: false },
                                                     { value: "value3", checked: false },
                                                     { value: "value4", checked: false }
                                                 ]
                                             }
                                                    ]
                                                    $scope.selected = []
                                                    $scope.checkValues = function () {
                                                        angular.forEach($scope.mytabs, function (value, index) {
                                                         var selectedItems = $filter('filter')(value.values, { checked: true });
                                                         angular.forEach(selectedItems, function (value, index) {
                                                             $scope.selected.push(value);
                                                         });
                                
                                                        });
                                                    console.log($scope.selected);
                                                    };
                                                });
                                        </script>
                                    </body>
                                </html>
                                

                                【讨论】:

                                  【解决方案28】:

                                  这是相同的 jsFillde 链接,http://jsfiddle.net/techno2mahi/Lfw96ja6/

                                  这使用可在http://vitalets.github.io/checklist-model/ 下载的指令。

                                  这是一个很好的指令,因为您的应用程序将经常需要此功能。

                                  代码如下:

                                  HTML:

                                  <div class="container">
                                      <div class="ng-scope" ng-app="app" ng-controller="Ctrl1">
                                          <div class="col-xs-12 col-sm-6">
                                              <h3>Multi Checkbox List Demo</h3>
                                              <div class="well">  <!-- ngRepeat: role in roles -->
                                                  <label ng-repeat="role in roles">
                                                      <input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
                                                  </label>
                                              </div>
                                  
                                              <br>
                                              <button ng-click="checkAll()">check all</button>
                                              <button ng-click="uncheckAll()">uncheck all</button>
                                              <button ng-click="checkFirst()">check first</button>
                                              <div>
                                                  <h3>Selected User Roles </h3>
                                                  <pre class="ng-binding">{{user.roles|json}}</pre>
                                              </div>
                                  
                                              <br>
                                              <div><b/>Provided by techno2Mahi</b></div>
                                          </div>
                                  

                                  JavaScript

                                  var app = angular.module("app", ["checklist-model"]);
                                  app.controller('Ctrl1', function($scope) {
                                    $scope.roles = [
                                      'guest',
                                      'user',
                                      'customer',
                                      'admin'
                                    ];
                                    $scope.user = {
                                      roles: ['user']
                                    };
                                    $scope.checkAll = function() {
                                      $scope.user.roles = angular.copy($scope.roles);
                                    };
                                    $scope.uncheckAll = function() {
                                      $scope.user.roles = [];
                                    };
                                    $scope.checkFirst = function() {
                                      $scope.user.roles.splice(0, $scope.user.roles.length);
                                      $scope.user.roles.push('guest');
                                    };
                                  });
                                  

                                  【讨论】:

                                  • HTML 格式不正确 - 开始标签 &lt;div&gt; 多于结束标签 &lt;/div&gt;。你遗漏了什么吗?
                                  【解决方案29】:

                                  试试我的宝贝:

                                  **

                                  myApp.filter('inputSelected', function(){
                                    return function(formData){
                                      var keyArr = [];
                                      var word = [];
                                      Object.keys(formData).forEach(function(key){
                                      if (formData[key]){
                                          var keyCap = key.charAt(0).toUpperCase() + key.slice(1);
                                        for (var char = 0; char<keyCap.length; char++ ) {
                                          if (keyCap[char] == keyCap[char].toUpperCase()){
                                            var spacedLetter = ' '+ keyCap[char];
                                            word.push(spacedLetter);
                                          }
                                          else {
                                            word.push(keyCap[char]);
                                          }
                                        }
                                      }
                                      keyArr.push(word.join(''))
                                      word = [];
                                      })
                                      return keyArr.toString();
                                    }
                                  })
                                  

                                  **

                                  然后对于任何带有复选框的 ng-model,它将返回您选择的所有输入的字符串:

                                  <label for="Heard about ITN">How did you hear about ITN?: *</label><br>
                                  <label class="checkbox-inline"><input ng-model="formData.heardAboutItn.brotherOrSister" type="checkbox" >Brother or Sister</label>
                                  <label class="checkbox-inline"><input ng-model="formData.heardAboutItn.friendOrAcquaintance" type="checkbox" >Friend or Acquaintance</label>
                                  
                                  
                                  {{formData.heardAboutItn | inputSelected }}
                                  
                                  //returns Brother or Sister, Friend or Acquaintance
                                  

                                  【讨论】:

                                    最近更新 更多