How to $watch multiple variables?

后端 未结 4 1145
天命终不由人
天命终不由人 2021-02-02 17:36

I do have two $scope variables. They are called $scope.image and $scope.titleimage.

Basically the store the same type of contents.

4条回答
  •  忘了有多久
    2021-02-02 18:22

    $watch method accepts a function as first parameter (beside a string). $watch will "observe" the return value of the function and call the $watch listener if return value is changed.

    $scope.$watch(
      function(scope){
        return {image: scope.image, titleImage: scope.titleImage};
      }, 
      function(images, oldImages) {
        if(oldImages.image !== images.image){
          console.log('Image changed');
        }
        if(oldImages.titleImage !== images.titleImage){
          console.log('titleImage changed');
        }
      }, 
      true
    ); 
    

    Also you might observe a concatenated value, but that doesn't let you know which one of the observed values actually changed:

    $scope.$watch('image + titleImage',
      function(newVal, oldVal) {
        console.log('One of the images have changed');
      }
    ); 
    

    And you can also watch an array of scope variables:

    $scope.$watch('[image, titleImage]',
      function(images, oldImages) {
        if(oldImages[0] !== images[0]){
          console.log('Image changed');
        }
        if(oldImages[1] !== oldImages[1]){
          console.log('titleImage changed');
        }
      },
      true
    ); 
    

提交回复
热议问题