ng-options 不选择选项数组中的最后一项

ng-options not selecting last item in option array

我有一个奇怪的问题,我无法在 Plunker 上重现。当在模型中设置第一个选项 'user' 时,select 会正确显示它并将其设置为 'user'。当我加载另一个具有角色的用户时:'admin',select 设置为空白选项。

在我的控制器中我定义:

$scope.roles = ['user', 'admin'];

我的 $scope.user 对象如下所示:

{
   "_id": "54f1f8f7e01249f0061c5088",
   "displayName": "Test1 User",
   "provider": "local",
   "username": "test1",
   "__v": 0,
   "updated": "2015-03-02T07:41:42.388Z",
   "created": "2015-02-28T17:20:55.893Z",
   "role": "admin",
   "profileImageURL": "modules/users/img/profile/default.png",
   "email": "test1@user.com",
   "lastName": "User",
   "firstName": "Test1"
}

在我看来:

<select id="role" class="form-control" data-ng-model="user.role" data-ng-options="role for role in roles"></select>

当我反转角色数组 $scope.roles = ['admin', 'user']; 时,管理员会正确显示,并且 'user' 不会被设置为 selected。

奇怪的是,如果我向数组添加第三个项目 $scope.roles = ['user', 'admin', 'joe']; 那么前两个 'user' 和 'admin' 将被正确设置 selected,最后一个'joe'不会。

有什么想法吗?

---更新---

生成的 select 标记如下所示:

<select id="role" class="form-control ng-pristine ng-valid" data-ng-options="role for role in roles" data-ng-model="user.role">
    <option value="? string:joe ?"></option>
    <option value="0" selected="selected" label="admin">admin</option>
    <option value="1" label="user">user</option>
    <option value="2" label="joe">joe</option>
</select>

我发布的是 解决方法,但不是解决方案,也不是对上述问题的解释。如果有人知道为什么会发生这种情况,以及如何使用数组进行这项工作,请分享,我很乐意接受它作为答案。

我将选项从简单数组更改为对象数组:

$scope.roles = [{name:'Admin',value:'admin'},{name:'User', value:'user'}];

我的观点是:

<select data-ng-model="user.role" data-ng-options="role.value as role.name for role in roles"></select>

感谢 Ilya Luzyanin 的帮助和指导!

我按照你的建议做了所有的组合,但是没有出现错误。

请看我的测试:

http://plnkr.co/edit/jzfhD3D60fhj8yFqBqgJ?p=preview

<h3>select</h3>
<select ng-model="role" ng-options="item for item in roles"></select>
<h3>original</h3>
<select id="role" class="form-control" data-ng-model="user.role" data-ng-options="role for role in roles"></select>

尝试验证您的 angularjs 版本。可能是特定版本错误。

刚刚与此作斗争。我的模型 $scope.details.source 被 ajax 填充,导致了这个问题。 (即,当 ajax 返回时,select 不会初始化数组中的最后一项,其他值初始化正常)。我确实找到了解决方法。我有

$scope.sources = ["1", "2", "3", "4", "5", "6", "7", "8"];
<select ng-model="details.source" ng-options="item for item in sources"> </select>

并将其更改为:

$scope.sources = [{index:0, value:"1"}, {index:1, value:"2"}, {index:2, value:"3"}, {index:3, value:"4"}, {index:4, value:"5"}, {index:5, value:"6"}, {index:6, value:"7"}, {index:7, value:"8"}];
<select ng-model="details.source" ng-options="item.index as item.value for item in sources"> </select>

我发现当模型在控制器中初始化时问题不存在,而不是 ajax。不知道为什么......但它有效。

可能晚了,但这里有一个对我有帮助的解决方案。我总是添加一个虚拟的不可见选项,它位于列表的最后并且永远不会被选中。

<select class="form-control" 
        ng-options="r as r for r in myList | orderBy track by r"
        ng-model="item">
    <option ng-show="false"></option> <!-- TRICK: select last value too -->
</select>