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

问题描述

我想只要3范围内的变量已经改变了指令重新呈现HTML。前两个都只是整数,第三个是一个数组。

我们有 $ watchGroup 看几个变量,我们有 $观看 objectEquality 作为第三个参数,我们有 $ watchCollection 这就好比 $观看,但与 objectEquality 暗示的保证。

有没有写一个类似的$表的方式?

  $ $范围watchGroup(['数字1','编号2','myArray的'],回调,真正的)。 //如此objectEquality


解决方案

嘛,好像watchGroup不支持深手表。所以,很可能你可以做一个黑客,通过与来自手表的功能传递价值观的阵列注册匿名深刻的观察家。

  $范围。$表(函数(){
     返回['数字1','编号2','myArray的']图。(angular.bind($范围,$范围$ EVAL));
  },功能(newV){
      的console.log(newV);
  },真正);

或只是从任何继承范围添加此功能的rootScope效用函数和访问它。

  .RUN(函数($ rootScope){
  $ rootScope.deepWatchGroup =功能(EXP,回调){
    如果收益率(angular.isArray(EXP)|| $ thisScope手表!); //或者记录一些错误,如果阵列不是传入或上下文是不是一个真正的范围对象   VAR thisScope =这个,//获取范围
        evalFunc = angular.bind(thisScope,thisScope $ EVAL); //一个必然的eval FUNC     thisScope。$表(函数(){
        返回exp.map(evalFunc); //返回评估值数组
     }回调,真正的);
   }
});

和从你的控制器做的:

  $ scope.deepWatchGroup(['数字1','编号2','myArray的'],功能(newV){
  的console.log(newV);
});

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.

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.

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

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

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

Demo

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

and from your controller do:

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

Demo

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

10-29 21:52