-->

Assigning ng-model to checkboxes generated by ng-r

2020-02-09 04:27发布

问题:

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

回答1:

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>

</div>
{{myCountry.selected}}

JS:

$scope.myCountry = {
    selected:{}
};