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

问题描述 投票:2回答:4

我有一个奇怪的问题,我无法在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": "[email protected]",
   "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'将不会被设置为选中。

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

有任何想法吗?

---更新---

生成的选择标记如下所示:

<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>
angularjs ng-options angularjs-ng-options
4个回答
0
投票

我和你建议的所有组合,但错误不会发生。

请查看我的测试:

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版本。也许可以是特定版本错误。


1
投票

刚刚完成了与此斗争。我的模型$ scope.details.source正在被ajax填充,从而导致问题。 (即当ajax返回时,select不会init到数组中的最后一项,其他值init'ed OK)。我确实找到了解决方法。我有

$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时,问题不存在。 Donno为什么......但它确实有效。


0
投票

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

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

$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的帮助和指示!


0
投票

可能迟到了,但这是一个帮助我的解决方案。我总是添加一个虚拟的隐形选项,它是列表中的最后一个,永远不会被选中。

<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>
© www.soinside.com 2019 - 2024. All rights reserved.