1

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?

Markus
  • 1,565
  • 6
  • 26
  • 57
  • 2
    After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization. – nweg May 20 '15 at 17:39
  • read more about what the arguments are – charlietfl May 20 '15 at 17:40
  • the problem is that in both execution cases `newVal` and `oldVal` are exactly the same. I just double checked it – Markus May 20 '15 at 17:43
  • Or just suppress the first event like in this answer: http://stackoverflow.com/a/16950610/4910019 – gyantasaurus May 20 '15 at 18:17
  • it doesn't change anything since it gets triggered at the same time twice – Markus May 20 '15 at 18:57

2 Answers2

3

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*/
    }
});
MBielski
  • 6,628
  • 3
  • 32
  • 43
  • the problem is that in both execution cases `newVal` and `oldVal` are exactly the same. I just double checked it – Markus May 20 '15 at 17:47
  • Yes, I face the same problem. I have added a condition to return, if the values are same, but yet.. it fires twice. – Thilak Rao Jun 18 '15 at 08:02
0

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