AngularJS选择预选不起作用

时间:2014-02-10 15:56:01

标签: javascript angularjs

即使对象相等,预选也不会在选择字段中起作用:

<select ng-show="isEditMode(todo.id)" id="assignee" name="assignee" 
        ng-model="todo.assignee" required 
        ng-options="user.name for user in users">
</select>

todo.assignee包含一个用户对象,该对象应与用户匹配。

似乎Angular无法识别来自todo.assignee的User对象包含在用户中。我可以手动执行此映射吗?

显示选择时未选择任何值。我可以选择一个用户(来自用户)并保存记录没有任何问题。

控制器

$scope.todos = Todo.query();
$scope.users = User.query();

更新

根据评论的要求。给定对象的结构: 的 $ scope.todos

 [
{
    "id": 157,
    "description": "my description 0",
    "deadline": 1392073200000,
    "assignee": {
        "id": 34,
        "name": "User 1",
        "email": "user1@hotmail.com"
    },
    "comment": "my comment 0",
    "done": true
}
...
]

$ scope.users

[
{
    "id": 34,
    "name": "User 1",
    "email": "user1@hotmail.com"
},
{
    "id": 35,
    "name": "User 2",
    "email": "xxc@gmail.com"
},
{
    "id": 36,
    "name": "User 3",
    "email": "xx@hotmail.com"
}
]

选择的范围来自重复:

<tr ng-repeat="todo in todos | filter:query | filter:{assignee:queryAssignee} | filter:queryDone" ng-class="{danger: isDue(todo)}">
                    <td>

2 个答案:

答案 0 :(得分:5)

根据你的描述:

  

todo.assignee包含一个用户对象

但是你的选项'值是user.name个字符串,一个对象和一个字符串永远不会匹配。

所以,替换

ng-model="todo.assignee"

ng-model="todo.assignee.name"

更新:

使用ng-options="user.name as user.name for user in users"

完整答案:

<select ng-show="isEditMode(todo.id)" 
    ng-model="todo.assignee.name" required 
    ng-options="user.name as user.name for user in users">
</select>

Plnkr: http://plnkr.co/edit/A1XdMYmACNCr3OwBuFhk?p=preview

选择数组

中的值的标签

label:此表达式的结果将是元素的标签。表达式很可能是指值变量(例如value.propertyName)。

你可以在这里参考: http://docs.angularjs.org/api/ng.directive:select

UPDATE2:

要修复副作用,您可以使用带有分隔值和显示名称的选项

<select ng-model="todo.assignee" required>
    <option ng-repeat="user in users" value="{{user}}" ng-selected="todo.assignee.name === user.name">
        {{user.name}}
    </option>
</select>

Plnkr: http://plnkr.co/edit/6tzP9ZexnYUUfwAgti9b?p=preview

说明:

在:

当您选择其中一个选项时,它会为模型todo.assignee.name指定选项值,因此只需更改名称。

todo.assignee.name = "User 3" // like this

todo.assignee // didn't change the id & email
/* {"id": 34,
    "name": "User 1",
    "email": "user1@hotmail.com"} */

但是,现在:

When you select one of option, it assign object value to model todo.assignee, so let what you want.

todo.assignee.name = { 
    "id": 36,
    "name": "User 3",
    "email": "user3@hotmail.com"
} // like this

todo.assignee // now change the whole value
/* {"id": 36,
    "name": "User 3",
    "email": "user3@hotmail.com"} */

答案 1 :(得分:2)

也许它对其他人有用:

<select ng-show="isEditMode(todo.id)" id="assignee" name="assignee" 
        ng-model="todo.assignee" required 
        ng-options="user as user.name for user in users track by user.id">
</select>

神奇的技巧在于“track by user.id”

https://docs.angularjs.org/api/ng/directive/ngOptions