所有
我对Angular指令很新,我想知道如何将$ watch合并在一起,例如:
如果我渲染一个图表指令,数据更改或宽度变化或高度变化将导致渲染,但是当初始阶段时,所有这三个可能一起变化,导致图表渲染三次,但只有一个渲染需要
由于
答案 0 :(得分:0)
查看lodash库,尤其是debounce
方法。有了它,你可以做类似的事情:
$scope.render =_.debounce($scope.oldRenderingMethod);
然后在每个事件处理程序中:
_.defer($scope.render);
debounce
注意,函数的执行频率不是每x秒(查看文档),而defer
确保画布的渲染不会对其产生负面影响。你的反应能力。
答案 1 :(得分:0)
一些事情:
您可以在监视功能中检查新值和旧值,并查看是否未设置旧值。
$scope.$watch('myvariable', function (newVal, oldVal) {
if (oldVal && newVal !== oldVal) {
//the old value was defined (initialized)
//and the new one is different (changed)
}
}
您还可以通过将动作包装在settimeout中来实现与lodash的defer()相同的功能。这两者基本上都会将操作推送到队列中,以便在下一个摘要周期中运行。
$scope.$watch('myvariable', function (newVal, oldVal) {
if (newVal !== oldVal) {
setTimeout(function() {
//do stuff
}, 0); //you don't need to actually set the timer, it will still push to the next cycle
}
}
如果没有代码示例,这只是您需要做的最佳猜测。