Angularjs在ng选项中比较两个对象
我有两个对象数组。 一个非常简单的例子:Angularjs在ng选项中比较两个对象,angularjs,Angularjs,我有两个对象数组。 一个非常简单的例子: $scope.genres = [ { id: '123', name: 'Genre 1' }, { id: '124', name: 'Genre 2' }, { id: '125', name: 'Genre 3' } ]; $scope.selectedGenres = [{ id: '123',
$scope.genres = [
{
id: '123',
name: 'Genre 1'
},
{
id: '124',
name: 'Genre 2'
},
{
id: '125',
name: 'Genre 3'
}
];
$scope.selectedGenres = [{
id: '123',
name: 'Genre 1'
}];
我使用类型填充选择
<select style="height: 100px; width: 100%;"
multiple
ng-model="selectedGenres"
ng-options="option as option.name for option in genres"></select>
我意识到自己在做:$scope.selectedGenres=[$scope.genres[0]代码>
工作原理与对象引用相同
有没有办法比较这两个对象是否相等,而不是它们的引用
示例:angular.equals
可能就是您要寻找的:
将以下内容添加到您的ng选项“track by option.id”
将自动选择该选项。这在你的例子中起作用,我想这就是你想要做的 在您的示例中,您的对象没有相同的属性,因此在使用angular.equals时,它们不会相等。selectedGenres对象上有一个“$$hashKey”属性(angular添加了该属性),因为您不是指定跟踪属性。$scope.genres数组中的对象没有“$$hashKey”属性。这就是angular.equals返回false的原因
如果在ng options表达式中添加track by属性,则会解决此问题
ng-options="option as option.name for option in genres track by option.id"
你不能通过引用匹配的用例是什么?我有一个API。一个调用返回$scope.genres,另一个调用返回$scope.selectedGenres。我在演示中通过添加console.log(angular.equals($scope.selectedGenres,$scope.genres[0])尝试了这一点代码>。。。返回false
ng-options="option as option.name for option in genres track by option.id"