将 ng-model 分配给由 ng-repeat 生成的复选框 [英] Assigning ng-model to checkboxes generated by ng-repeat
问题描述
我已经设置了一个包含国家/地区列表的 json,并附有 ID 和国家/地区代码:
看起来像这样:
$scope.countries = [{"name":"阿富汗","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
指令为每个国家/地区创建复选框输入.
<label><input type="checkbox" ng-model="{{country.id}}" ng-true-value="'{{country.name}}'" ng-false-value="''">{{country.name}}</label>
但是,当我运行代码时,我只能显示以下内容:
位置此处的复选框 {{country.name}}
如果我删除重复的 ng-model
部分,我的复选框生成正常,但我需要一个唯一的 ng-model
附加到每个复选框
ng-model="{{country.id}}"
我将如何附加唯一的 ng-model
值?
这个答案(在 ng-repeat 中生成 ng-model)确实不提供唯一的 ng-model
值
我会建议你,使用:
<label><input type="checkbox" ng-model="myCountry.selected[country.id]" ng-true-value="'{{country.name}}'" ng-false-value="''">{{country.name}}</label>
{{myCountry.selected}}JS:$scope.myCountry = {已选择:{}};
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
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:{}
};
这篇关于将 ng-model 分配给由 ng-repeat 生成的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!