当听众是date()函数的角度观照不起作用 [英] Angular watcher does not work when listener is the Date() function
问题描述
我知道我要求有一个非常简单的答案(我是新来的角,它确实需要很大的勇气来这里问这个;)的问题。我有一个显示时间这样的指令:
I know I am asking a question that has an extremely simple answer (I am new to angular and it did take a lot of courage to ask this here ;). I have a directive that displays the time like this:
Application.Directives
.directive('theClock', function(){
return {
retrict: 'EA',
templateUrl: 'partials/partial.clock.html',
link: function(scope, elem, attrs) {
scope.dTime = Date();
scope.$watch( function(scp){ return Date(); }, function(newVal){
scope.dTime = newVal;
}
);
}
};
});
我期望的时间将更新每$消化周期,但事实并非如此。我知道,使用的setInterval
OT $超时
是另一种方式来做到这一点,但我真的不希望有一个时钟,我想知道为什么更新不会发生。顺便说一句我没叫 $适用()
检查后 $$阶段
- 没有帮助
I expect that the time would update every $digest cycle but it does not. I know that using setInterval
ot $timeout
is another way to do this, but I dont really want a clock, I want to understand why the update does not happen. BTW I did call $apply()
after checking for $$phase
- did not help
感谢您。
推荐答案
在$手表功能默认情况下是按引用比较的对象,这是字符串/数值更快,罚款,但不会像日期复杂对象的工作 - 日期可能改变,但它是永诺同一日期对象,所以基准不会改变。
The $watch function compares objects by reference by default, which is faster and fine for string/number values, but won't work for complex objects like Date - the Date may change, but it is allways the same Date object, so the reference doesn't change.
这是避免巨大的阵列重相等测试。
This is to avoid heavy equality tests on gigantic arrays.
现在,虽然这可能工作(注意$表函数的第三个参数设置为true):
Now, while this may work (note the third parameter of the $watch function set to true):
scope.dTime = new Date();
scope.$watch( function(scp){ return new Date(); }, function(newVal){
scope.dTime = newVal;
}, true
);
这将每一次可能触发更改事件它轮询$手表功能(意为每一个应用程序循环)
It will probably trigger a change event every time it polls the $watch function (meaning every single app cycle)
如果你想,如果触发每一秒,从日期返回秒(),喜欢的东西回报Math.floor(新的Date()。的valueOf()/ 1000)。那么,你想设置DTIME。
If you want if to trigger every second, return the seconds from Date(), with something like return Math.floor(new Date().valueOf()/1000). Then set dTime as you wish.
更新
虽然角度的检查将与归期工作()
,这个问题是由于角度的脏检查系统 - 它只会检查$手表功能的变化时触发在模型(意为$范围内定义的模型)。
While angular's checking would work with return Date()
, the problem is due to angular's dirty checking system - it will only check the $watch functions when a change is triggered on a model (meaning a model defined within a $scope).
这 Plnkr ,从Valentyn Shybanov的分叉,可以作为一个例子 - 时钟功能触发模型的改变,而这种改变触发$手表功能
This Plnkr, forked from Valentyn Shybanov's, can serve as an example - a clock function triggers a change on a model, and that change triggers a $watch function.
同时,通知这个版本,使用window.setTimeout。它只能使用$ apply方法来通知angularJS一个变化发生的工作。
ALSO, notice this version, that uses window.setTimeout. It can only work using an $apply method to notify angularJS that a change has occured.
这篇关于当听众是date()函数的角度观照不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!