如何使用对象设置ng-options默认值?

时间:2014-09-16 12:19:19

标签: angularjs ng-options

如果我设置值下拉值,因为对象未按预期工作。

例如: HTML:

<select ng-model="selected" ng-options="lst as lst.name for lst in list"></select>

JS:

$scope.list=[{'name':'Person-1','age':23},
  {'name':'Person-2','age':14},
  {'name':'Person-3','age':32},
  {'name':'Person-4','age':34},
  {'name':'Person-5','age':67},
  {'name':'Person-6','age':12}];

   $scope.selected = {'name':'Person-3','age':32};

如果我将值指定为$ scope.selected = $ scope.list [0]正常工作。但是现在我如何指定一个对象进行选择。

我附上了plunker链接:http://plnkr.co/edit/WJo0W688s5NDN7kZYOPR?p=preview

2 个答案:

答案 0 :(得分:1)

这是因为您分配的对象不在$ scope.list中。然而它看起来一样,但它是一个不同的对象。 $scope.list[0]正在工作,因为它指向$ scope.list所具有的相同对象引用。

请参阅更新的plunker,以便您了解。

Updated

如果你有对象,那么你需要通过比较属性并查找适当对象的索引来迭代$scope.list,并使用该索引来分配所选对象,如。

$scope.selected = $scope.list[matchIndex]

答案 1 :(得分:-1)

$scope.selected = $scope.list[0];

这是您设置默认选项

的方法
相关问题