Assigning ng-model to checkboxes generated by ng-repeat

主宰稳场 提交于 2019-12-29 04:42:11

问题


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


来源:https://stackoverflow.com/questions/27917218/assigning-ng-model-to-checkboxes-generated-by-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!