同时,消防回调$观察多个属性只有一次 [英] $observe multiple attributes at the same time and fire callback only once

查看:117
本文介绍了同时,消防回调$观察多个属性只有一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能执行一些回调一次评估后,所有(或只有部分)的属性指令(无隔离的范围)。属性是真正伟大的传递配置的指令。问题是,你可以观察单独每个属性与火回调几次。

I wonder is it possible to execute some callback only once after evaluation all (or only some) attributes of directive (without isolated scope). Attributes are really great to pass configuration to the directive. The thing is that you can observe each attribute separately and fire callback several times.

在这个例子中,我们有没有这observs两个属性隔离范围指令:姓名。任何更改后动作回调被触发:

In the example we have a directive without isolated scope which observs two attributes: name and surname. After any change action callback is fired:

HTML

<button ng-click="name='John';surname='Brown'">Change all params</button>
<div person name="{{name}}" surname="{{surname}}"></div>

JS

angular.module('app', []).

directive('person', function() {
  return {
    restrict: 'A',
    link: function($scope, $elem, $attrs) {
        var action = function() {
          $elem.append('name: ' + $attrs.name + '<br/> surname: ' + $attrs.surname+'<br/><br/>');
        }
        $attrs.$observe('name', action);
        $attrs.$observe('surname', action);
    }
 }
});

所以效果是,在点击更改姓名后,动作回调被触发两次:

So the effect is that after changing name and surname during one click, action callback is fired twice:

name: 
surname: Brown

name: John
surname: Brown

所以,问题是:能动作与双方姓名值只有一次发射改变了

So the question is: can action be fired only once with both name and surname values changed?

推荐答案

您可以使用 $观看来评价一个自定义函数,而不是一个特定的模式。

You can use $watch to evaluate a custom function rather than a specific model.

$scope.$watch(function () {
  return [$attrs.name, $attrs.surname];
}, action, true);

这将在所有运行 $消化的周期,当 $观看检测返回数组(或然要构建你的函数的返回值)不匹配的旧值,回调参数 $观看将闪光。如果你使用一个对象作为返回值虽然,确保在最后一个参数离开真正 $观看 $观看将做一次深层比较。

That will be run on all $digest cycles, and if $watch detects the return array (or however you want to structure your function's return value) doesn't match the old value, the callback argument to $watch will fire. If you do use an object as the return value though, make sure to leave the true value in for the last argument to $watch so that $watch will do a deep compare.

这篇关于同时,消防回调$观察多个属性只有一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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