5

使用 angular,我想创建一个带有我选择的 id(对象的实际 id 属性)的值的选择列表,并且我想将它与 ng-model 指令正确绑定。

这是我尝试过的:

<select ng-model="selectedPersonId"                 
ng-options="p.id as p.name for p in People track by p.id"></select>

$scope.People = [
    { name : "Fred", id : 1 },
    { name : "Joe", id : 2 },
    { name : "Sandra", id : 3 },
    { name : "Kacey", id : 4 },
    { name : "Bart", id : 5 }
];

$scope.setTo1 = function(){
    $scope.selectedPersonId = 1;
}

http://jsfiddle.net/b7dyadnr/

这里选择选项值是正确的值(值是人中的人的id)并且文本是正确的。但是绑定不起作用,因此如果我设置 $scope.selectedPersonId 的值,则选择不会反映在列表中。

我知道我可以让它像这样工作:

<select ng-model="selectedPersonId"                 
ng-options="p.id as p.name for p in People"></select>

http://jsfiddle.net/rgtbn2f5/

在那里我可以设置 $scope.selectedPersonId 并且更改会反映在列表中。但是,选择列表选项值中使用的 id 不是实际人的 id !

<option value="0">Fred</option> <!--option value is 0 which is not the true id of fred -->
<option value="1" selected="selected">Joe</option>
...

我想像这样使用它,除了我希望 angular 在选择选项值中使用人的真实 id,而不是数组的索引或它使用的任何东西。

如果你想知道我为什么要这样使用它,那是因为 id 被发送到 API 并且模型也可以使用 querystring 设置,所以我必须让它像这样工作。

4

1 回答 1

7

Had the same issue while back. And it appears that p.id will only work in one place either in select or in trackexpr. The only way it worked for me (value was set to id) was like this:

<select 
ng-model="selectedPerson"                 
ng-options="p as p.name for p in People track by p.id"></select>

Though the code for selecting person with id = 1 would look pretty ugly:

$scope.setTo1 = function () {
    $scope.selectedPerson = $scope.People.filter(function (item) {
        return item.id == 1
    })[0];
}

Here is jsfiddle.

This is because you have to assign ng-model the same item you have in ng-options collection since they are compared by reference. This is from angular documentation:

Note: ngModel compares by reference, not value. This is important when binding to an array of objects. See an example in this jsfiddle.

So I gave up eventually and let Angular to set option value to whatever it needs since it would allow me to make assignemnet as simeple as: $scope.selectedPersonId = 1

于 2014-09-17T08:23:43.510 回答