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

12
我已经设置了一个包含国家ID和国家代码的国家列表json:
它看起来像这样:
$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值?

这个答案(在ng-repeat内生成ng-model)没有提供一个唯一的ng-model值。


尝试移除 {{country.id}} 周围的 {{}} - simeg
当我这样做时,所有复选框都会得到相同的ng-model值,但我需要每个复选框都有唯一的ng-model值。 - ocajian
1
尝试将 ng-repeat 设置为 country in countries track by $index,并将 ng-model 设置为 countries[$index] - simeg
这似乎只会为所有复选框提供相同的ng-model - ng-model="countries[$index]" - ocajian
1个回答

31

我建议你使用:

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

这是我认为会起作用的,但由于某些原因,每次重复我的复选框时,我仍然得到相同的ng-model值。我对于每个复选框都得到myCountry.selected[country.id]。 - ocajian
我猜你是通过检查元素来进行检查的。它会显示相同的结果。将模型传递给控制器并在控制台中输出结果,你就能得到答案了。 - Ved
哦,你说得对。我当时使用了检查元素。谢谢你的帮助。 - ocajian
对我来说可以工作。但如何遍历myCountry.selected? - Anushree Acharjee
@AnushreeAcharjee,你遇到了什么问题?迭代很容易,对吧? - Ved
你能告诉我你的顾虑吗? - Ved

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接