我正在努力学习AngularJS,我目前的研究都在观察。我有一个 JSFiddle ,代码如下。我试图看一个形式原始状态。但是,在初始化myText和表单时,摘要会导致$ watch事件处理程序触发。虽然我可以为newValue !== oldValue
添加if检查并且只在这种情况下继续检查,但这似乎是对每个手表都要做的额外工作。是否可以在不添加自定义代码的情况下阻止手表触发变量初始化?
<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 +"'");
});
}]);