[英]Angular Js: Can you set the default value for a select in conjunction with using 'track by' in ng-options
The best method to set the values for your options in your select list, seems to be to use 'track-by' (using a.id as a.name seems to be out-dated) in your ng-options directive. 在选择列表中设置选项值的最佳方法似乎是在ng-options指令中使用“ track-by”(使用a.id作为a.name似乎已过时)。 However, when I use 'track by', I am no longer able to set the default value using ng-model. 但是,当我使用“ track by”时,我不再能够使用ng-model设置默认值。
Take for example, this plunkr: http://plnkr.co/edit/OZCal9ZkCQeqnQJY0WP9?p=preview 例如,以下示例: http ://plnkr.co/edit/OZCal9ZkCQeqnQJY0WP9?p=preview
<select ng-model="class.team.leader" ng-options="student.name for student in curTeam.students track by student._id">
Currently, the plunkr correctly sets the default value. 当前,plunkr正确设置默认值。 However, if you change it to use 'track by', like in the code above, it does not work. 但是,如果您将其更改为使用“跟踪依据”,如上面的代码中所示,则无法使用。
track by
doesn't work like that. track by
不是那样的。 It's used to compare a property on both objects rather than checking for object equality. 它用于比较两个对象的属性,而不是检查对象是否相等。 ie obj1.trackBy === obj2.trackBy
rather than obj1 === obj2
. 即obj1.trackBy === obj2.trackBy
而不是obj1 === obj2
。
For example, change your default model to: 例如,将默认模型更改为:
$scope.class = {
team: {
leader: { _id: 2, name: 'Dave', status: 0 }
}
};
Without track by
this wouldn't work as it's a different object to what's in the students array. 如果没有track by
这将是行不通的,因为它与students数组中的对象是不同的对象。 But with track by
angular will compare the _id
properties to decide equality. 但是track by
角度track by
将比较_id
属性来确定相等性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.