I update the $scope
in my Javascript and I would like to know if the form is now valid or not. How can I force validation to occur or wait for Angular to run the validation?
This is some sample code. When I click the button, $scope.validateA = true
makes the form invalid, but not straight away. So on the next line of code, if I look at $scope.abForm.$valid
, it is still true
.
var validationApp = angular.module('validationApp', []);
validationApp.controller('mainController', function($scope) {
$scope.submitA = function() {
$scope.validateA = true;
//force validation to run here??
alert($scope.abForm.$valid);
};
});
<div ng-app="validationApp" ng-controller="mainController">
<form name="abForm">
a
<input ng-required='validateA' ng-model='a'>
<button type="button" ng-click="submitA()">submit a</button>
</form>
</div>
See the sample in Plunker
You're right in that Angular hasn't $digest
ed the changes in the form yet in order to set the form's valid/invalid properties.
You need to wait for the next $digest
cycle. You can't force it but you can wait for it, if you use $timeout
without a wait time you can force your alert statement to wait for the next $digest
cycle where any inputs for the form will have been verified.
http://plnkr.co/edit/mjPuDPhS8bnbN15lO7yF?p=preview
I added this to your plunker:
validationApp.controller('mainController',function($scope,$timeout){
$scope.submitA = function(){
$scope.validateA = true
$timeout(function(){
alert($scope.abForm.$valid);
});
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With