Angularjs比较ng-options中的两个对象

时间:2015-01-23 17:28:42

标签: angularjs

我有两个对象数组。 一个非常简单的例子:

$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]]; 将作为对象引用工作是相同的。

有没有办法比较两个对象的相等性而不是它们的引用?

示例:http://jsbin.com/cizuyitadu/6/edit

3 个答案:

答案 0 :(得分:8)

在您的示例中,您的对象没有相同的属性,因此在使用angular.equals时它们不会相等。您的selectedGenres对象上有一个'$$ hashKey'属性(angular添加此属性),因为您不是指定跟踪属性。 $ scope.genres数组中的对象没有'$$ hashKey'属性。这就是为什么angular.equals返回false的原因。

如果您在ng-options表达式中按属性添加曲目,则会解决问题。

ng-options="option as option.name for option in genres track by option.id"

答案 1 :(得分:7)

将以下内容添加到ng-options“track by option.id”

<select style="height: 100px; width: 100%;"
                    multiple
                    ng-model="selectedGenres"
                    ng-options="option as option.name for option in genres track by option.id"></select>

这将自动选择该选项。这适用于你的例子,我认为这是你想要做的?

答案 2 :(得分:0)

angular.equals可能就是你要找的东西:

https://docs.angularjs.org/api/ng/function/angular.equals