Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS force validation or wait for $scope.myForm.$valid to refresh

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

like image 817
Ande Avatar asked Aug 07 '14 13:08

Ande


1 Answers

You're right in that Angular hasn't $digested 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);
        });
    };
});
like image 155
m.e.conroy Avatar answered Sep 27 '22 22:09

m.e.conroy