Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Angular Material Design Checkboxes to an Array in Controller

I have a group of material design checkboxes and I would like to bind their values to an array in my controller.

To accomplish this I used the first method described in this SO answer. While the values are properly being added and removed from the list, the boxes no longer display as "checked" when I click on them. My code is below and I also recreated the problem in this codepen.

HTML for my checkbox

<md-checkbox 
    ng-repeat="site in websites" 
    value="{{site}}" 
    ng-checked="selection.indexOf(site) > -1" 
    ng-click="toggleSelection(site)"> 
    {{site}}
</md-checkbox>

JavaScript from Controller

  $scope.websites = ['Facebook', 'Twitter', 'Amazon'];
  $scope.selection = ['Facebook'];
  $scope.toggleSelection = function toggleSelection(site) {
    var idx = $scope.selection.indexOf(site);

    // is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // is newly selected
    else {
      $scope.selection.push(site);
    }
  };
});
like image 200
dsal1951 Avatar asked Apr 05 '15 02:04

dsal1951


1 Answers

Try changing this:

ng-checked="selection.indexOf(site) > -1" 

to this:

ng-checked="{{selection.indexOf(site) > -1}}" 

Worked for me: http://codepen.io/anon/pen/xbNOmE

like image 65
jarz Avatar answered Nov 14 '22 23:11

jarz