Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

angularjs - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:{}
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...