【问题标题】:set selected value in ng-option based on ng-repeat根据 ng-repeat 在 ng-option 中设置选定值
【发布时间】:2016-03-01 04:42:17
【问题描述】:
<li class="list-group-item" ng-repeat="entity in displayedProjectRoles">
    <div>
        <strong>Role: </strong> 
        <select
            ng-model="project.role" 
            ng-options="option as option.name for option in project_role"
            ng-required="true"
            id="project_role"
            class="form-control">
        </select>
    </div>
</li>

如何根据ng-repeatentity.role 上的值设置模型project.role 的值?我尝试了ng-selected,甚至在ng-model 中使用了entity.role,但它无法正常工作。

这是显示的项目角色中的数据

[
  {
    "empid": 2,
    "role": "employee"
  },
  {
    "empid": 1,
    "role": "pm"
  }
]

在 project_role 中

[
  {
    "id": 1,
    "name": "employee"
  },
  {
    "id": 2,
    "name": "pm"
  }
]

所以基本上displayProjectRoles中的角色值与project_role中的名称匹配

【问题讨论】:

  • 给定数组输入
  • 尝试设置 project.role = { "id": 1, "name": "employee" } 作为测试,看看是否绑定
  • 什么是project_role?请尝试包括所有内容。考虑构建一个 plunker,它有助于理解并为您提供有效的解决方案。

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


【解决方案1】:

This 是角度选择的一个很好的例子。

基本上,选择的ng-model 必须与要绑定的ng-option 值匹配。在您的示例中,project.role 必须与您的ng-options 中的option 完全相等。请注意,这是特定类型的,所以它是

option.id as option.name for option in project_role

option.id == 1 然后project.role == '1' 不会绑定

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2016-12-08
    • 2014-02-16
    • 2015-04-19
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多