3

I am trying to learn AngularJS, my current studies are on $watch. I have a JSFiddle with the code below. I am attempting to watch the a forms pristine state. However, at the time of initialization for myText and the form the digest causes the $watch event handlers to fire. Although I can add an if check for newValue !== oldValue and only continue in that case, this seems like extra work to do on every watch. Is it possible to prevent the watch from firing for a variable initialization without adding custom code?

<div ng-controller="pristineCheck">
    <form name="myForm">
        <input type="text" id="myInput" ng-model="myText">
            <div>Form Valid: {{myForm.$valid}}</div>
            <div>Form Pristine: {{myForm.$pristine}}</div>
            <div>Form Dirty: {{myForm.$dirty}}</div>
    </form>
</div>

angular.module('app', [])
.controller('pristineCheck', ['$scope',
    function($scope){
        $scope.myText = "Hello World";

        $scope.$watch('myText', function(newValue, oldValue){
            alert("myText changed from '" + oldValue + "' to '" + newValue +"'");
        });

        $scope.$watch('myForm.$pristine', function(newValue, oldValue){
            alert("pristine changed from '" + oldValue + "' to '" + newValue +"'");
        });

        $scope.$watch('myForm.$dirty', function(newValue, oldValue){
            alert("dirty changed from '" + oldValue + "' to '" + newValue +"'");
        });
    }]);
JabberwockyDecompiler
  • 3,318
  • 2
  • 42
  • 54
  • 3
    It's not the case that the variable initialization causes your $watchers to fire, since angular doesn't see that action, it's the digest. When digest runs it will call every watcher to check if the value has changed since last time and eventually call the listener. But to do the comparison it has to know the last value, so at the very beginning it has to initialize the "last values" with something, so it runs the first digest just for this purpose, and that's the moment when your watchers are getting called. Making the `oldV !== newV` is very common and inescapable (afaik). – jcz Apr 01 '15 at 18:55
  • @getOffMyLawn You are correct that it is the digest that is causing the watch to fire, I was not accurate on that. I will update my post to make that more clear. – JabberwockyDecompiler Apr 01 '15 at 18:59

0 Answers0