I am using the <md-checkbox> with the 'indeterminate' attribute provided by Angular Material to update an array based on the checkboxes selected. However, the Array is only updated based on ng-click, not on ng-change. Therefore, checking the "Select All" item, will not insert the values into the array.
Consider this codepen.
How can I update the addData function based on ng-change?
ng-change does require ng-model but you actually only need a model for this exampleselected property on each item and use this as modelselected by using https://docs.angularjs.org/api/ng/filter/filterController:
controller('AppCtrl', function($scope, $filter) {
$scope.items = [{num: 1},{num: 2}, {num: 3}, {num: 4},{num: 5}];
$scope.isIndeterminate = function() {
var selected = $filter('filter')($scope.items, {selected: true}).length;
console.log(selected);
return selected !== 0 && selected !== $scope.items.length;
};
$scope.allChecked = function() {
return $filter('filter')($scope.items, {selected: true}).length === $scope.items.length;
};
$scope.toggleAll = function() {
var selected = $filter('filter')($scope.items, {selected: true}).length;
var newSelected = selected < $scope.items.length;
angular.forEach($scope.items, function(item) {
item.selected = newSelected;
});
};
});
Markup:
<div>
<fieldset class="demo-fieldset">
<legend class="demo-legend">Using
<md-checkbox> with the 'indeterminate' attribute </legend>
<div layout="row" layout-wrap="" flex="">
<div flex-xs="" flex="50">
<md-checkbox aria-label="Select All" md-indeterminate="isIndeterminate()" ng-click="toggleAll()" ng-checked="allChecked()">
<span ng-if="isChecked()">Un-</span>Select All
</md-checkbox>
</div>
<div class="demo-select-all-checkboxes" flex="100" ng-repeat="item in items">
<md-checkbox ng-model="item.selected">
{{ item.num }}
</md-checkbox>
</div>
</div>
</fieldset>
<div ng-repeat="data in items | filter: {selected: true}" style="display: inline-block">
{{data.num}},
</div>
</div>
Adapted codepen: http://codepen.io/kuhnroyal/pen/gMLGxL
Edit per comment: http://codepen.io/kuhnroyal/pen/ZOBaNO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With