如何 $watch 多个变量? [英] How to $watch multiple variables?

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

问题描述

我确实有两个 $scope 变量.它们被称为 $scope.image$scope.titleimage.

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

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

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 方法接受一个函数作为第一个参数(字符串旁边).$watch 会观察"函数的返回值,如果返回值改变,就会调用 $watch 监听器.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆