$watchGroup vs $watchCollection?

后端 未结 2 907
-上瘾入骨i
-上瘾入骨i 2021-02-18 17:07

There\'re 2 ways to watch a group of variables in Angular. But what\'s the difference between them?

They both seem to do shallow watches. Are there situations where one

2条回答
  •  清酒与你
    2021-02-18 17:16

    Here's an example of where you'd use each one.

    $scope.data = ['Abc', 'Bcd', 'Cde', 'Def'];
    $scope.$watchCollection('data', function(){...});
    // responds to changes within $scope.data
    // The following line will trigger the watch function:
    $scope.data[0] = 'FOO';
    

    -

    $scope.data = ['Abc', 'Bcd', 'Cde', 'Def'];
    $scope.$watchGroup('data', function(){...});
    // responds to changes on the properties (or functions, etc.)
    // Any angular expression can be used in $scope.data
    // The following line will trigger the watch function:
    $scope.Abc = 'FOO';
    

提交回复
热议问题