mercredi 21 janvier 2015

Bind two arrays into one group of checkboxes - angularjs

I have a JSON object that contains an array of items (which have name and id) and also an array of selected items (which would have only ids of the items from previous array that has been selected).


What I want to render on HTML page is a group of checkboxes (i.e. one checkbox per available item) that will be also binded to the second array of selected items. I know how to do it in JQuery, but I wonder if there is a clean "angularJS-way" of handling this and binding it somehow to the model.


So when the page is rendered, I want certain checkboxes to be selected (as per the second array) and also whenever I select/deselect an item, it should either appear/disappear from that array.


Hope I explained properly - I cannot change the structure of JSON source object as it's retrieved from the server and I have no control over it.


JSFiddle below - its obviously not working - I dont know what should I bind ng-model to for each check box.


http://ift.tt/1ANNTW4



<span ng-repeat="item in object.stock">
<label class="checkbox" for="{{item.id}}">
<input type="checkbox" ng-model="object.selected[item.id]" id="{{item.id}}" />
{{item.name}}<br/>
</label>
</span>



$scope.object = {"stock":[ { "name": "Item1", "id": "1" } ,
{"name": "Item2", "id": "2" },
{"name": "Item3", "id": 3}], "
selected":{"ids":[1,2]}}


Any help appreciated.





Aucun commentaire:

Enregistrer un commentaire