admin管理员组

文章数量:1312825

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?

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?

Share Improve this question asked May 19, 2014 at 10:03 thomauxthomaux 19.7k10 gold badges81 silver badges105 bronze badges 1
  • 3 I'm not 100% sure but I don't think there's a way to know. Couldn't prove it though. Interesting question – edi9999 Commented May 19, 2014 at 10:04
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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.

本文标签: javascriptAngular obtain cause of a watch to be triggeredStack Overflow