0

This is probably easy and I'm missing something very basic. I'm generating several md-checkboxs using ng-repeat over an array. How can I clear this array without breaking the $digest cycle? selectedItems is an array of objects which holds data based on the checkboxes the user checked.

<div id="container">
    <span class="network-wrapper" ng-repeat="item in $ctrl.dataSource">
        <md-checkbox ng-model="$ctrl.networksCheckboxes[item.id]"
                     ng-checked="$ctrl.exists(item, $ctrl.selectedItems)"
                     ng-change="$ctrl.toggle(item, $ctrl.selectedItems)">
           {{ item.name }}
        </md-checkbox>
    </span>
    <button class="btn btn-danger" ng-click="$ctrl.reset()">Reset</button>
</div>

JS:

public toggle (item, list) {
    var idx = list.indexOf(item);
    if (idx > -1) {
      list.splice(idx, 1);
    }
    else {
      list.push(item);
    }
  };

 public exists (item, list) {
   return list.indexOf(item) > -1;
 };

public reset(){
    this.selectedItems.length = 0; //Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Alex
  • 1,982
  • 4
  • 37
  • 70
  • 2
    I have a feeling this is related to having both `ng-model` and `ng-checked` on the same element – Frank Modica Jan 09 '19 at 14:19
  • Maybe.. But `ng-model` should exist on the checkbox in order to function if I'm not mistaken – Alex Jan 09 '19 at 14:20
  • 1
    Right but `ng-model` changes the state of the checkbox based on your model (and vice versa), so why do you need `ng-checked` too? I have a feeling they are conflicting with each other – Frank Modica Jan 09 '19 at 14:21
  • `ng-checked` gets a value based on the selection. if that item does not exists in the `selectedItems` array add it and return `true` to check the box – Alex Jan 09 '19 at 14:26
  • ng-model + ng-change OR ng-checked + ng-click -- choose one – Petr Averyanov Jan 09 '19 at 14:31
  • 1
    `ng-model` is also changing your checkbox state based on `$ctrl.networksCheckboxes[item.id]`. So I think you should stick to having `$ctrl.networksCheckboxes[item.id]` determine whether the checkbox is checked, and set that value to `true/false` whenever it has to change – Frank Modica Jan 09 '19 at 14:35
  • Thanks guys, I managed to solve this using your comments – Alex Jan 09 '19 at 15:41

0 Answers0