Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

Bind a list of checkboxes in AngularJS

I have a list of checkboxes as following :

<div ng-repeat="formationType in formationTypeList">
  <label>
  <input type="checkbox" class="md-warn md-align-top-left"
    ng-model="formationSelection[$index]" 
    ng-true-value="{{formationType}}" 
    name="formationSelection[]">
    {{ formationType.nom }}
  </label>
</div>

As you can see this checkboxes are initialized with values in formationSelection[] array.

And when I check some checkbox the value of this checkbox is added to that array.

The formationTypeList contains a list of objects, each object is attached to a checkbox.

In my scenario the first time I have the formationSelection[] empty so when I check some checkboxes and I send my form the values in that array will be stored in a database, and when I back o my application I want to see the checkboxes I've selected so I populate that array whith values from the database and then I can see the ones wich was selected.

The problem I have is the checkboxs are only selected in one case if I have in formationSelection[] the first element or the first, second elements or the first, second and third elements, but when I have for example the second and the fourth elemnts, they are not selected.

this is a plunker for the working case :

http://plnkr.co/edit/I7NK8Tkw3Rzwh1Zj2X78?p=preview

and this is a plunker for the non working case :

http://plnkr.co/edit/82FDQlhTtd09scs9cCDz?p=preview

Why I'm getting this behavior, and how can I solve it ?

Upvotes: 0

Views: 61

Answers (1)

Yin Gang
Yin Gang

Reputation: 1443

Keep formationSelection length the same as formationTypeList, it will work.

$scope.formationSelection = (function(selection,list){
  var result = new Array(list.length);
  Array.prototype.map.call(selection,function(val,index){
    var pos = Array.prototype.map.call(list,function(v,i){
      return v.codeFormation;
    }).indexOf(val.codeFormation);
    result[pos] = val;
  });
  return result;
})($scope.formationSelection,$scope.formationTypeList);

Plunker here.

Upvotes: 1

Related Questions