简体   繁体   中英

Strange behaviour when checking/unchecking all items in a list of checkboxes

In a list of checkboxes it should be possible to check/uncheck all items by pushing a button. But the following code only works partially:

<div ng-controller="Controller">
    <button ng-click="setCheckStateForAll(true)">All</button>
    <button ng-click="setCheckStateForAll(false)">None</button>
    <ul>
        <li ng-repeat="item in items">
            <input type="checkbox" id="{{item.name}}" ng-checked="item.isChecked"/>
            <label for="{{item.name}}">{{item.name}}</label>
        </li>
    </ul>
</div>
function Controller($scope) {
    $scope.items = [
        { name: "A", isChecked: true },
        { name: "B", isChecked: true },
        { name: "C", isChecked: true },
        { name: "D", isChecked: true },
        { name: "E", isChecked: true }
    ];

    $scope.setCheckStateForAll = function(value) {
      for (var i = 0; i < $scope.items.length; i++)
        $scope.items[i].isChecked = value;
    };
}

↗jsFiddle

By default all items are checked and if "None" is clicked all items are deselected as expected.

But if then "A" is checked and "None" is clicked again, "A" stays checked (but it shouldn't). But if "All" is clicked, all items are checked.

What is there wrong?

Instead of ng-checked use ng-model to bind to ìtem.isChecked . ngModel provides bidirectional binding while ng-checked does not.

<input type="checkbox" id="{{item.name}}" ng-model="item.isChecked"/>

JSFIDDLE demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM