2015-01-13 41 views
10

产生的复选框,我已经建立了包含附着有ID和国家代码的国家的列表的JSON:勘定NG-模型伍重复

它看起来像这样:

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

如何LD我去附加一个独特的ng-model值?

这个答案(Generate ng-model inside ng-repeat)不提供独特的ng-model

+0

尝试删除'{{}}'周围的'{{国家.id}}' – simeg

+0

当我这样做时,我得到的所有复选框都是相同的ng-model值,但是我需要为每个复选框设置一个唯一的ng-model值。 – ocajian

+1

尝试将'ng-repeat'设置为'country in country track by $ index '和'ng-model'到'countries [$ index]' – simeg

回答

18

我会建议你,使用:

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

这是我认为会工作,但由于某种原因,我仍然得到相同的ng模型值为我的复选框的每一个重复。我得到myCountry.selected [country.id]为每个checbox – ocajian

+0

我想,你正在通过检查元素来检查它。它会显示相同的。将模型传递给控制器​​并控制结果。你会得到你的答案。 – Ved

+0

哦,你是对的。我正在使用检查元素。感谢您的帮助 – ocajian