Rafael code Rafael code - 1 year ago 490
AngularJS Question

Angular material checkbox - add function to ng-checked

I am using the

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?

Answer Source
  • ng-change does require ng-model but you actually only need a model for this example
  • you have 3 arrays basically holding the same items, you can do with just one
  • add a selected property on each item and use this as model
  • filter the array on items that are selected by using https://docs.angularjs.org/api/ng/filter/filter


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;
    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;   


    <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
        <div class="demo-select-all-checkboxes" flex="100" ng-repeat="item in items">
          <md-checkbox ng-model="item.selected">
            {{ item.num }}
    <div ng-repeat="data in items | filter: {selected: true}" style="display: inline-block">

Adapted codepen: http://codepen.io/kuhnroyal/pen/gMLGxL

Edit per comment: http://codepen.io/kuhnroyal/pen/ZOBaNO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download