angularjs实现 checkbox全选、反选的思考

时间:2021-11-10 10:42:56

需求

angularjs实现 checkbox全选、反选的思考

1 还有个总的checkbox 负责全选和反选
2 当每一项开头都选中checkbox的时候,上面的全选自动选上
3 当全选后,取消其中一项的checkbox,全选取消



<div ng-controller="myController"> <label for="flag">全选 <input id="flag" type="checkbox" ng-model="select_all" ng-change="selectAll()"> </label> <ul> <li ng-repeat="i in list"> <input type="checkbox" ng-model="i.checked" ng-change="selectOne()"> <span>{{id}}</span> </li> </ul> </div>

  

var app = angular.module('myApp',[]);
app.controller('myController', ['$scope', function ($scope) {
    $scope.list = [
        {'id': 101},
        {'id': 102},
        {'id': 103},
        {'id': 104},
        {'id': 105},
        {'id': 106},
        {'id': 107}
    ];
    $scope.m = [];
    $scope.checked = [];
    $scope.selectAll = function () {
        if($scope.select_all) {
            $scope.checked = [];
            angular.forEach($scope.list, function (i) {
                i.checked = true;
                $scope.checked.push(i.id);
            })
        }else {
            angular.forEach($scope.list, function (i) {
                i.checked = false;
                $scope.checked = [];
            })
        }
        console.log($scope.checked);
    };
    $scope.selectOne = function () {
        angular.forEach($scope.list , function (i) {
            var index = $scope.checked.indexOf(i.id);
            if(i.checked && index === -1) {
                $scope.checked.push(i.id);
            } else if (!i.checked && index !== -1){
                $scope.checked.splice(index, 1);
            };
        })

        if ($scope.list.length === $scope.checked.length) {
            $scope.select_all = true;
        } else {
            $scope.select_all = false;
        }
        console.log($scope.checked);
    }
}]);

  

参考