选择/取消所有复选框 - AngularJS纳克重复

问题描述:

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

I have a structure which looks like this: 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;
    });

};


});

在检查所有选择或取消选择所有其他复选框被选中。但是,当全选时,我取消的项目之一,我想检查所有被取消。

When check all is selected or deselected, all other checkboxes are selected. But when "Check All" is selected, and I deselect one of the items, I want "Check All" to be deselected.

在此先感谢!

(PS:感谢deeptechtons为的jsfiddle)

(PS: Thanks to deeptechtons for the JSFiddle)

如果您使用的是角1.3+可以使用 getterSetter NG-模型选项来解决这个问题,并避免手动跟踪的 allSelected 状态

If you are using Angular 1.3+ you can use getterSetter from ng-model-options to solve this and avoid manually keeping track of the allSelected state

HTML

<input type="checkbox" ng-model="allSelected" ng-model-options="{getterSetter: true}"/>

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();
    }
}

http://jsfiddle.net/2jm6x4co/