$rootScope.$watch triggered twice

自闭症网瘾萝莉.ら 提交于 2020-01-02 23:08:22

问题


I want to trigger a new Chat once the variable newChat is being changed like this:

$rootScope.newChat = {
  roomId: roomId,
  friendId: friendId
};

in my ChatController I $watch the variable like this:

$rootScope.$watch('newChat', function (data) { /*do stuff*/ }

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.

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?


回答1:


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*/
    }
});



回答2:


I fixed this problem like this

$rootScope.$watch('someValue', function (){
                /* rewrite into a new scope */
                $scope.someValue = $rootScope.someValue;
            });
 $scope.$watch('someValue', function (){/*To do*/});


来源:https://stackoverflow.com/questions/30356554/rootscope-watch-triggered-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!