问题
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