本文介绍了如何使用具有对象相等性的 $watchGroup 或深入观察组中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当三个范围变量发生变化时,我想要一个指令来重新呈现 HTML.前两个只是整数,第三个是数组.

I want a directive to re-render HTML whenever three scope variables have changed. The first two are just integers, the third is an array.

我们有 $watchGroup 来观察几个变量,我们有 $watchobjectEquality 作为第三个参数,我们有 $watchCollection 类似于 $watch,但隐含了 objectEquality.

We have $watchGroup to watch several variables, we have $watch with objectEquality as a third parameter, and we have $watchCollection which is like $watch, but with objectEquality implied.

有没有办法写一个类似这样的$watch?

Is there a way to write a $watch similar to this?

$scope.$watchGroup(['number1', 'number2', 'myArray'], callback, true); // true for objectEquality

推荐答案

看来 watchGroup 不支持 deep watch.因此,您可能可以通过使用从 watch 函数传入的值数组注册一个匿名深度观察者来进行黑客攻击.

Well it seems like watchGroup does not support a deep watch. So probably you can do a hack, by registering an anonymous deep watcher with array of values being passed in from the watch function.

$scope.$watch(function(){
     return ['number1','number2','myArray'].map(angular.bind($scope, $scope.$eval));
  }, function(newV){
      console.log(newV);
  },true);

演示

或者只是将此函数添加为 rootScope 上的实用函数,并从任何继承的范围访问它.

or just add this function as utility function on the rootScope and access it from any inherited scopes.

.run(function($rootScope){
  $rootScope.deepWatchGroup = function(exp, callback){
    if(!angular.isArray(exp) || !thisScope.$watch) return; //Or log some error if array is not passed in or the context is not really a scope object

   var thisScope = this, //get scope
        evalFunc = angular.bind(thisScope, thisScope.$eval); //and a bound eval func

     thisScope.$watch(function(){
        return exp.map(evalFunc); //return array of evaluated values
     }, callback,true);
   }
});

并从您的控制器执行:

$scope.deepWatchGroup(['number1','number2','myArray'],function(newV){
  console.log(newV);
});

演示

这篇关于如何使用具有对象相等性的 $watchGroup 或深入观察组中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:46