选中/取消选中所有复选框 - AngularJS ng-repeat

Ram*_*mya 3 checkbox angularjs angularjs-ng-repeat

我有一个看起来像这样的结构:http://jsfiddle.net/deeptechtons/TKVH6/

<div>
<ul ng-controller="checkboxController">
    <li>Check All
        <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
    </li>
    <li ng-repeat="item in Items">
        <label>{{item.Name}}
            <input type="checkbox" ng-model="item.Selected" />
        </label>
    </li>
</ul>
</div>

angular.module("CheckAllModule", [])
.controller("checkboxController", function checkboxController($scope) {


$scope.Items = [{
    Name: "Item one"
}, {
    Name: "Item two"
}, {
    Name: "Item three"
}];
$scope.checkAll = function () {
    if ($scope.selectedAll) {
        $scope.selectedAll = true;
    } else {
        $scope.selectedAll = false;
    }
    angular.forEach($scope.Items, function (item) {
        item.Selected = $scope.selectedAll;
    });

};


});
Run Code Online (Sandbox Code Playgroud)

选中或取消选中全部选中后,将选中所有其他复选框.但是当选择"全部检查"并取消选择其中一个项目时,我希望取消选中"全部检查".

提前致谢!

(PS:感谢JSFiddle的deeptechtons)

rob*_*rob 5

如果您使用的是Angular 1.3+,则可以使用getterSetterfrom ng-model-options来解决此问题,并避免手动跟踪allSelected状态

HTML:

<input type="checkbox" ng-model="allSelected" ng-model-options="{getterSetter: true}"/>
Run Code Online (Sandbox Code Playgroud)

JS:

var getAllSelected = function () {
    var selectedItems = $scope.Items.filter(function (item) {
        return item.Selected;
    });

    return selectedItems.length === $scope.Items.length;
}

var setAllSelected = function (value) {
    angular.forEach($scope.Items, function (item) {
        item.Selected = value;
    });
}

$scope.allSelected = function (value) {
    if (value !== undefined) {
        return setAllSelected(value);
    } else {
        return getAllSelected();
    }
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/2jm6x4co/