Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: obtain cause of a $watch to be triggered

A very short question: In Angular, is there any way whatsoever to obtain the "root cause" of a $watch to be triggered?

Let's say you have the following JavaScript code:

$scope.$watch("foo", function(value){
    // here I'd like to know if the change is triggered 
    // due to change in ngModel or through ngClick
};

$scope.changeFoo = function(){
    $scope.foo = "bar"
};

And this is the HTML:

<input ng-model="foo">
<button ng-click="changeFoo()">Change Foo > Bar</button>

In my $watch I'd like to know what caused it to be fired. In this case, was it a change in ngModel or was my value changed in the function of ngClick?

like image 309
thomaux Avatar asked May 19 '14 10:05

thomaux


2 Answers

No, there is no way to do that with the current implementation.

$watch are triggered running a function called $apply. That function doesn't know who triggered it.

You are going to need another perspective to fix your problem.

like image 146
Jesus Rodriguez Avatar answered Nov 20 '22 15:11

Jesus Rodriguez


No, we cant know which triggers it. Check this question how-to-get-the-dom-element-that-triggered-ng-change, maybe trying to write a custom directive to pass more info to your controller is a possible way to get trigger.

like image 1
jackypan1989 Avatar answered Nov 20 '22 17:11

jackypan1989