问题描述
一旦要更改变量newChat
,我想触发新的聊天记录:
I want to trigger a new Chat once the variable newChat
is being changed like this:
$rootScope.newChat = {
roomId: roomId,
friendId: friendId
};
在我的ChatController
我$watch
这样的变量中:
in my ChatController
I $watch
the variable like this:
$rootScope.$watch('newChat', function (data) { /*do stuff*/ }
在第一次重新加载页面后,它可以在我的页面上正常使用.但是对于第一次加载,此$watch
会被触发两次,从而导致聊天的其他部分出现问题.
this works on my page after the first reload of the page without any problems. But for the first load this $watch
gets triggered twice which causes issues on some other parts of the chat.
我检查了newChat
的值.两次值完全相同.我的应用程序的其他部分没有使用$rootScope.newChat
变量
I checked the value of newChat
. Both times the value is exactly the same. No other parts of my application use the $rootScope.newChat
Variable
那是为什么,我该如何解决?
Why is that and how can I fix this?
推荐答案
每个$ digest循环运行时,都会触发每个手表.您需要做的是检查新值与旧值.
Every watch will get triggered when a $digest cycle runs. What you need to do is check the new value vs. the old value.
$rootScope.$watch('newChat', function (newValue, oldValue) {
if(newValue !== oldValue){
/*do stuff*/
}
});
这篇关于$ rootScope.$ watch触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!