将ng-model分配给ng-repeat生成的复选框

时间:2015-01-13 07:49:57

标签: angularjs angularjs-ng-repeat ng-repeat

我已经设置了一个json,其中包含附有ID和国家/地区代码的国家/地区列表:

看起来像这样:

$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"}
]

然后我使用ng-repeat指令为每个国家/地区创建复选框输入。

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

但是,当我运行代码时,我只会显示以下内容:

地点 复选框{{country.name}}

如果我删除重复的ng-model部分我的复选框生成正常但我需要将唯一的ng-model附加到每个复选框

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

我如何附加唯一的ng-model值?

此答案(Generate ng-model inside ng-repeat)未提供唯一的ng-model

1 个答案:

答案 0 :(得分:24)

我会建议你,使用:

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