【问题标题】:Assigning ng-model to checkboxes generated by ng-repeat将 ng-model 分配给 ng-repeat 生成的复选框
【发布时间】:2021-12-18 01:26:50
【问题描述】:

我设置了一个 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

【问题讨论】:

  • 尝试删除{{country.id}}周围的{{}}
  • 当我这样做时,我会为所有复选框获得相同的 ng-model 值,但我需要为每个复选框设置一个唯一的 ng-model 值
  • 尝试将ng-repeat 设置为country in countries track by $indexng-model 设置为countries[$index]
  • 这似乎也只为所有复选框提供了相同的 ng-model - ng-model="countries[$index]"

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


【解决方案1】:

我会建议你,使用:

<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]
  • 我猜,您正在通过检查元素来检查它。它会显示相同的。将模型传递给控制器​​并控制台结果。你会得到你的答案。
  • 哦,你是对的。我正在使用检查元素。感谢您的帮助
  • 为我工作。但是如何遍历 myCountry.selected?
  • @AnushreeAcharjee 你遇到了什么问题?迭代容易正确吗?
猜你喜欢
  • 2015-06-09
  • 2016-04-27
  • 2014-07-12
  • 2016-07-26
  • 1970-01-01
  • 2015-08-13
  • 2017-11-19
  • 2015-07-26
  • 1970-01-01
相关资源
最近更新 更多