如何$观看多个变量?

pow*_*tac 12 angularjs angularjs-scope

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

基本上存储相同类型的内容.我想现在跟踪其中任何一个更新.但到目前为止,我无法弄清楚如何在一个$scope.$watch()回调中跟踪两个变量.

// How can I watch titleimage here as well?
$scope.$watch('image', function(media) {
    console.log('Media change discoverd!');
}); 
Run Code Online (Sandbox Code Playgroud)

Ste*_*wie 30

$watchmethod接受函数作为第一个参数(在字符串旁边). $watch将"观察"函数的返回值,并在返回值更改时调用$ watch监听器.

$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
); 
Run Code Online (Sandbox Code Playgroud)

您也可能会观察到连接值,但这并不能让您知道哪个观察值实际发生了变化:

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

您还可以观看一系列范围变量:

$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
); 
Run Code Online (Sandbox Code Playgroud)

  • 你不是说`oldImages.titleImage !== images.titleImage`吗?(你有两次 `oldImages`。) (2认同)

Ben*_*esh 15

Stewie的建议会奏效.但是有一千种方法可以给这只猫留下皮肤.我提出,如果你正在观察两个不同的值,那么为它们设置两个手表并没有任何问题,它们之间有共享功能:

功能性编程救援!

使用函数创建函数非常棒.

function logChange(expr) {
   return function(newVal, oldVal) {
      console.log(expr+ ' has changed from ' + oldVal + ' to ' + newVal);
   };
}

$scope.$watch('image', logChange('image'));
$scope.$watch('titleImage', logChange('titleImage'));
Run Code Online (Sandbox Code Playgroud)

或者......你甚至可以将手表设置包装在它自己的功能中(更不用说令人兴奋了,IMO):

function logChanges(expr) {
   $scope.$watch(expr, function(newVal, oldVal) {
      console.log(expr+ ' has changed from ' + oldVal + ' to ' + newVal);
   });
};

logChanges('image');
logChanges('titleImage');
Run Code Online (Sandbox Code Playgroud)

..但是我有一千个,你说呢?

//assuming the second function above
angular.forEach(['image', 'titleimage', 'hockeypuck', 'kitchensink'], logChanges);
Run Code Online (Sandbox Code Playgroud)