本文介绍了如何看$多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 $范围变量。他们被称为 $ scope.image $ scope.titleimage

基本上存储相同类型的内容。我想,当他们中的任何一个被更新到现在的轨道。但到目前为止,我无法弄清楚如何有一个 $范围。$表()回调跟踪两个变量。

  //我怎么能看着titleimage在这里呢?
$范围。$腕表('形象',函数(媒体){
    的console.log(媒体变革discoverd!');
});


解决方案

$观看方法接受一个函数作为第一个参数(字符串旁)。
$观看将观察的函数的返回值,如果返回值被改变调用$手表听众。

$范围。$手表(
  功能(适用范围){
    返回{图片:scope.image,titleImage:scope.titleImage};
  },
  功能(图像,oldImages){
    如果(oldImages.image!== images.image){
      的console.log('形象改变');
    }
    如果(oldImages.titleImage!== images.titleImage){
      的console.log('titleImage改为');
    }
  },
  真正
);

另外你可能会注意到一个连接的值,但是,这并不让你知道哪些观测值中的一个实际改变:

$范围。$表(形象+ titleImage',
  功能(的newval,OLDVAL){
    的console.log('其中一个图像已经改变');
  }
);

而且你还可以观看范围的数组变量:

$范围。手表$('[图像,titleImage]',
  功能(图像,oldImages){
    如果(oldImages [0]!==图像[0]){
      的console.log('形象改变');
    }
    如果(oldImages [1]!== oldImages [1]){
      的console.log('titleImage改为');
    }
  },
  真正
);

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

Basically the store the same type of contents. I want to track now when either one of them gets updated. But so far I could not figure out how to have two variables tracked in a single $scope.$watch() callback.

// How can I watch titleimage here as well?
$scope.$watch('image', function(media) {
    console.log('Media change discoverd!');
}); 
解决方案

$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
); 

这篇关于如何看$多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 04:38