Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning ng-model to checkboxes generated by ng-repeat

I have set up a json containing a list of countries with an ID and Country code attached:

It looks like this:

$scope.countries = [
  {"name":"Afghanistan","id":"AFG","country-code":"004"},
  {"name":"Åland Islands","id":"ALA","country-code":"248"},
  {"name":"Albania","id":"ALB","country-code":"008"},
  {"name":"Algeria","id":"DZA","country-code":"012"}
]

I then use the ng-repeat directive to create checkbox inputs for every country.

<div ng-repeat="country in countries">
      <label><input type="checkbox" ng-model="{{country.id}}" ng-true-value="'{{country.name}}'" ng-false-value="''">{{country.name}}</label>
</div>

However when I run the code I only get the following to display:

Location checkbox here {{country.name}}

If I remove the ng-model part of the repeat my checkboxes generate fine but I need a unique ng-model to be attached to every checkbox

ng-model="{{country.id}}"

How would I go about attaching a unique ng-model value?

This answer (Generate ng-model inside ng-repeat) does not provide a unique ng-model value

like image 280
ocajian Avatar asked Jan 13 '15 07:01

ocajian


People also ask

How do I insert a checkbox in NG-repeat?

The AngularJS app HTML DIV consists of another HTML DIV with a CheckBox and Label elements. The ng-repeat directive has been applied to the HTML DIV in order to populate CheckBoxList i.e. List of multiple CheckBoxes from a JSON array. The ng-model attribute of the CheckBox has been assigned the Selected property.

What can I use instead of NG-repeat?

But ng-repeat is not the right thing to use when you have large datasets as it involves heavy DOM manipulations. And you should consider using ng-repeat with pagination. You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

What does ng-repeat do?

The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.


1 Answers

I will suggest you, use:

<div ng-repeat="country in countries">
  <label><input type="checkbox" ng-model="myCountry.selected[country.id]" ng-true-value="'{{country.name}}'" ng-false-value="''">{{country.name}}</label>
</div>

{{myCountry.selected}}

JS:

$scope.myCountry = {
    selected:{}
};
like image 66
Ved Avatar answered Oct 21 '22 08:10

Ved