AngularJS checkbox ng-repeat and selected objects?

Jakub Kuchar picture Jakub Kuchar · Feb 12, 2013 · Viewed 80.2k times · Source

I am trying to do it in proper way with less pain, but i can't figure out how to deal with ng-model and binding it to the selected list etc and moreover i need to populate that list in later time and keep selected objects in it.

categories = [ { "name": "Sport", "id": "50d5ad" } , {"name": "General", "id": "678ffr" } ]

    <span ng-repeat="category in categories">
      <label class="checkbox" for="{{category.id}}">
        <input type="checkbox" value="{{category.id}}" ng-model="??" ng-click="??" name="group" id="{{category.id}}" />
        {{category.name}}
      </label>
    </span>

I have to override the categories each time the list is populated since it will be pulled out from a server.

So I guess I need to have arrays and the second one will hold the selected objects?

If I am right, how do I preselect checkboxes?

Do I need ng-click in order call custom function to store the selected object in the other array?

Do I need ng-model in checkbox And what for?

What is the proper-way with less pain?

Answer

bmleite picture bmleite · Feb 12, 2013

I have to override the categories each time the list is populated since it will be pull out form server. So i quess i need to have arrays and the second one will hold the selected objects?

Yes, since it is a list you can/should use arrays. The information about the selected items/objects should be stored on your scope model (example below).

If I am right, how do I preselected checkboxes?

Save the ID's of the selected options/checkboxes on your model and let the ng-model do the rest.

Do I need ng-click in order call custom function to store the selected object in the other array?

No, you don't need it, ng-model is enough.

Do i need ng-model in check box? And what for?

Yes, you need it. The ng-model is responsible for storing the selected options on your model and for making the ('pre-')selection automatic.

jsfiddle http://jsfiddle.net/bmleite/PQvQ2/