2015-01-13 40 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