I'm still quite new to AngularJS and I think I'm having trouble understanding the timing with $scope. In a controller, I've setup a watcher for some model data that is bound to various form elements. The watcher fires off an ajax request when the data changes, except if the form is not valid. I'm checking the form validity with myForm.$valid. This is all pretty straight forward, however, except when the model data is updated in the controller, and not the form. The validations runs as expected, but form.$valid still has the previous value, not what it should be with the updated data. For example, if the form was previously valid, then I delete the model value bound to a required input, the watcher will fire because the model data has changed, but when I log the value of myForm.$valid it's value is still true, even though it should be false.
So my question is A. why is this happening?, but more importantly B. what is the correct way to handle what I am trying to accomplish? Would a custom directive make sense?
Here is a simplified example.
HTML:
<div ng-controller="MyCtrl">
<form name="myForm">
<input type="text" name="myField" ng-model="myData" required>
<button type="button" ng-click="myData=''">Delete</button>
</form>
<div>
The watcher says the form is: <strong>{{ formStatus }}</strong>
</div>
</div>
Controller:
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.myData = 'abc';
$scope.formStatus = '';
$scope.$watch('myData', function(newVal, oldVal) {
if (newVal != oldVal) {
console.log("my data changed");
console.log("my form valid = ", $scope.myForm.$valid);
$scope.formStatus = $scope.myForm.$valid ? 'Valid' : 'Invalid';
}
});
}]);