AngularJS checkbox ng-repeat and selected objects?

80,619

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/

Share:
80,619
Jakub Kuchar
Author by

Jakub Kuchar

I'm a Ruby on Rails fighter spun with AngularJS and Cordova, always finding time to refactor my code and not ashamed to publish it. I use my inner force to write tests.

Updated on July 14, 2020

Comments

  • Jakub Kuchar
    Jakub Kuchar almost 4 years

    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?