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 +"'");
});
}]);