$ rootScope.$ watch触发两次 [英] $rootScope.$watch triggered twice

查看:160
本文介绍了$ rootScope.$ watch触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦要更改变量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触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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