Angular JS force validation or awaiting $ scope.myForm. $ Valid to update

I am updating $scope

in my Javascript and I would like to know if the form is valid or not. How do I force a check or wait for Angular to run a check?

This is a sample code. When I click the button, $scope.validateA = true

it invalidates the form, but not immediately. So on the next line of code, if I look at $scope.abForm.$valid

, it doesn't care 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 sample in Plunker

+3


source to share


1 answer


You are correct that Angular did not change the $digest

changes in the form to set valid / invalid properties of the form.

You need to wait for the next cycle $digest

. You can't force it, but you can wait, if you use $timeout

no timeout, you can force the warning statement to wait for the next loop $digest

where any inputs for the form will be validated.

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);
        });
    };
});

      

+4


source







All Articles