如何使用AngularJS绑定到复选框值列表?

JavaScript

西门神奇

2020-03-11

我有几个复选框:

<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似乎只能将一个复选框的值绑定到控制器中的变量。

还有另一种方法可以使四个复选框绑定到控制器中的列表吗?

第728篇《如何使用AngularJS绑定到复选框值列表?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
猪猪小小 2020.03.11

在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});
};
神奇Tony古一 2020.03.11

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

<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
  }
];
小胖逆天 2020.03.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

Jim达蒙阳光 2020.03.11

我认为最简单的解决方法是在指定了“多个”的情况下使用“选择”:

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

否则,我认为您必须处理列表以构造列表(通过$watch()将模型数组与复选框绑定在一起)。

JinJin宝儿 2020.03.11

签出可有效管理复选框列表的指令。我希望这个对你有用。 清单模型

null 2020.03.11

使用字符串$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
};

此方法并非在所有情况下都适用,但易于实现。

乐蛋蛋 2020.03.11

由于您接受了不使用列表的答案,因此,我认为我的评论问题的答案是“不,它不必是列表”。我还给人一种印象,就是您可能正在使用HTML服务器端,因为示例HTML中出现了“ checked”(如果使用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最初设置某些复选框。

小提琴

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android