Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an invalid form is valid at first and right after turns out invalid?

In order to simplify things I made up a sample form to describe my question:

<form novalidate name="form">
  <input required name="foo" ng-model="my.foo">
</form>

And also a controller:

angular.module('sample', []).controller('MainController', function($scope) {
  $scope.$watch('form.$valid', function (valid) {
    console.log(valid);
  });
});

Expected result:

> false

Actual result:

> true
> false

Can anybody tell me why at first the form is valid and then becomes invalid (what it is supposed to be, by the way)?

Working demo

like image 234
Carlos Avatar asked May 19 '15 16:05

Carlos


1 Answers

I'm actually sure this is due to directives priority.

In angularJS <form> is actually a directive. required is another one.

Let supose we have a form without validation. The form is always valid. I'm pretty sure that now we can say that a form is valid by default.

The "form" directive have a higher priority than "required". It mean that at a point. Angular apply the "form" directive, and not the "required" one. This result in a valid form with an input with an unknown attribute "required". Next digest will analyze the "required" directive. It find that the input is empty and set valid to false.

As Omri said, it's a mater of directives priority and digest cycles.

like image 128
Okazari Avatar answered Oct 29 '22 16:10

Okazari