AngularJS $watch vs $watchCollection: which is better for performance?

前端 未结 3 2015
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 19:46

For watching an object scope variable, is $scope.$watch with objectEquality set to true OR $scope.$watchCollection better?

For

3条回答
  •  北海茫月
    2020-11-30 20:35

    $watchCollection is optimized for vector arrays [] where elements can be push

    and $watch is good for associative arrays objects {}

    $watchCollection will not watch for depth changes, is like watch with objectEquality set to false.

    If you already know to structure of the depth you can optimize like this:

      // ctrl watch ?
      $scope.$watch('filters', function(newVal, oldVal) {
        if(newVal !== oldVal) {
          // call with updated filters
        }
      });
    
      // ctrl watch ?
      $scope.$watch('filters.info', function(newVal, oldVal) {
        if(newVal !== oldVal) {
          // call with updated filters
        }
      });
    

提交回复
热议问题