简体   繁体   中英

AngularJS form validity within controller

From what I know, the $valid property (and other similar ones) are accessible with $scope.formname.inputname.$valid from the controller..

I've played around with this: http://plnkr.co/edit/oEfdMpI3URooJhRFfSUr?p=preview

this.validity = $scope.myForm.input.$valid; //ADDED THIS LINE

Why does this one line that I added in script.js break it? I would expect {{ctrl.validity}} to show up as true.

You added that line in a controller's constructor.

By the time that the constructor instance is created, the form in a view hasn't been compiled yet.

Try using $timeout to defer the execution of the line like this to make it works:

var ctrl = this;

$timeout(function () {
  ctrl.validity = $scope.myForm.input.$valid; //ADDED THIS LINE
});

Or if you want to keep them in sync, use $watch :

$scope.$watch('myForm.input.$valid', function (isValid) {
  ctrl.validity = isValid;
});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM