I wanted to set selected option in my dropdown list.
我想在下拉列表中设置选定的选项。
I have two ways of passing data into selects ng-model
我有两种将数据传递到select ng-model的方法
first: $scope.selectedTeam = $scope.teams[31];
second: $scope.selectedTeam = selectedTeamSrvs.getTeam()
my html select looks like this:
我的html选择如下:
<select ng-model="selectedTeam"
ng-options="team as team.name for team in teams | orderBy:'ID'">
</select>
and JSON.stringify($scope.teams[31]) === JSON.stringify(selectedTeamSrvs.getTeam())
gives true. Then why only first option sets selected option correctly?
而JSON.stringify($scope.teams[31]) == JSON.stringify(selectedTeamSrvs.getTeam())给出true。那么为什么只有第一个选项设置正确的选项?
1 个解决方案
#1
2
By default, ngModel compares by reference, not value.This is important when binding to an array of objects
默认情况下,ngModel是根据引用而不是值进行比较的。当绑定到对象数组时,这一点很重要
Second option is not setting correctly because selectedTeamSrvs.getTeam() returns a different instance of team, even though they are equal when stringified.
第二个选项没有正确设置,因为selectedteamsrv . getteam()返回一个不同的team实例,即使它们在字符串化时是相等的。
#1
2
By default, ngModel compares by reference, not value.This is important when binding to an array of objects
默认情况下,ngModel是根据引用而不是值进行比较的。当绑定到对象数组时,这一点很重要
Second option is not setting correctly because selectedTeamSrvs.getTeam() returns a different instance of team, even though they are equal when stringified.
第二个选项没有正确设置,因为selectedteamsrv . getteam()返回一个不同的team实例,即使它们在字符串化时是相等的。