質問

So I have a watch on scope A. Why does AngularJS evaluate it when a local variable on sibling scope B changes? The data model of scope A hasn't changed.

Here is a minimal example of this:

  • there is a custom watch on scope A.
  • the input element is bound to the text variable of scope B.
  • Note that the text is not shown, because it's not visible from scope A.

Controllers:

function Ctrl1($scope) {

    console.log($scope); // first scope

    // my custom watch expression
    var count = 0;
    $scope.$watch(function() {
        count++;
        console.log("call count: " + count);
    }, function() {
        // the listener does nothing
        // I'm just interested in when the watch expression is called
    });

}

function Ctrl2($scope) {        
    console.log($scope); // second scope        
}

HTML:

<div ng-app>
    <div ng-controller="Ctrl1">        
        {{text}}
    </div>
    <div ng-controller="Ctrl2">
        <input type="text" ng-model="text"></input>
    </div>
</div>

(Feel free to try this code here: http://jsfiddle.net/s3Wz5/4/ )

If you type some text in the input element (scope B), the custom watch of the scope A is evaluated. Why is this? Why doesn't AngularJS know that there are no changes to the data model of scope A whatsoever?

Update: Some clarification: I don't want to watch text. This is a performance related question, wondering why the watch is evaluated even though text cannot possibly be read from the other scope!

役に立ちましたか?

解決

Because $watch is evaluated in every digest cycle. Change value of a ng-model triggers digest cycle. This behavior is different from $scope.$digest(), which only triggers digestion on current and child scopes.

I think ng-model might NOT use $scope.$digest() internally. It might use some other mechanism to trigger digest after value changes.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top