【问题标题】:how to display option as selected in select box in angularjs?如何在angularjs的选择框中显示选项?
【发布时间】:2016-04-20 14:10:27
【问题描述】:

我无法设置 angularjs 中选择的选项

<tr ng-repeat="leader in filtered = (list | orderBy:sort.active:sort.descending) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
    <td>
       <select class="form-control mt10" name="leaderRole" ng-model="leader.role_id" ng-class="{ inputerror: !leader.role_id}">
          <option value="">Please select role</option>
          <option ng-repeat="role in employeeRole" ng-selected="{{leader.role_id == role.id}}" value="{{role.id}}">{{role.description}}</option>
       </select>
    </td>
</tr>

控制器部分

var leaders_list = angular.module('leaders_list'); //getter
leaders_list.controller('LeaderController',['$scope','$http','$filter',LeaderController]);
function LeaderController($scope,$http,$filter)
{
   $scope.list = [
      {
        "title": "XYZ",
        "name_first": "ABC",
        "name_last": "EFG",
        "email": "lmn@opq.com",
        "id": 1,
        "role_id": 3
      }
   ];

  $scope.employeeRole = [
    {
      "id": 2,
      "description": "JKL",
      "is_active": true
    },
    {
      "id": 3,
      "description": "STV",
      "is_active": true
    }
  ];
}

这里的 leader.role_id 是每个领导者的 role_id 的值,当我执行上述代码时,它没有显示我的值被选中。

如果我从选择框中删除 ng-model,它将显示我的值被选中。

Plunker 链接: https://plnkr.co/edit/qesu3J6mxJdS6bTjPXKI?p=info

谁能建议我如何做到这一点?

【问题讨论】:

  • 尝试从&lt;option&gt;&lt;/option&gt;中删除ng-selected="{{leader.role_id == role.id}}"
  • 你能显示一些你的控制器的代码吗?
  • 嗨@DhavalMarthak,我已经尝试过了,但没有成功。
  • 你能创建一个plunker来演示吗?
  • 嗨@Fidel90,我添加了控制器代码

标签: angularjs


【解决方案1】:

不按照建议使用 ng-options,会让自己的生活变得困难。

只需将您的选择替换为

<select class="form-control mt10" name="leaderRole" 
        ng-model="leader.role_id" ng-class="{ inputerror: !leader.role_id}"
        ng-options="role.id as role.description for role in employeeRole">
  <option value="">Please select role</option>
</select>

https://plnkr.co/edit/fW9O6BCDOl59aziTz7zX?p=preview

【讨论】:

  • 嗨@JB Nizet,感谢您的回答。我做了这类事情,但我做错了。
  • 嗨,谁能解释一下区别。在 ng-options="role.description for role in employeeRole track by role.id" 和 ng-options="role.id as role.description for role in employeeRole"。
  • 如文档中解释的,如果使用role.id as role.description,则模型值为ID,显示值为描述,而如果使用role.description,则模型值为角色本身(即整个对象),显示的值是描述。 track by 仅用于确定如何将 DOM 元素与数组元素关联,以防您刷新数组。
猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多