简体   繁体   中英

Toggle all in ng-repeat

I have a list of items that can be selected:

<div ng-repeat="item in items" ng-init="selected = false" ng-click="selected = !selected">
    ...
</div>

I want a simple checkbox outside of the list that will select all of the items IN the list. What's the prettiest Angular way to accomplish this?

You can create a function in your controller to loop through each item in your items array and set its selected property to true. Here's a sample of the function:

$scope.selectAll = function(selected) {
    angular.forEach($scope.items, function(item) {
        item.selected = selected;
    });
}

I made the function take an argument so you can re-use it to do an de-select all.

Next, you can create a button that will call this function, passing true as an argument.

<button type="button" ng-click="selectAll(true)">Select All</button>

Here's a very rudimentary jsfiddle for it: http://jsfiddle.net/x906p4qx/

Hope it helps!

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