5

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

Carlos
  • 4,949
  • 2
  • 20
  • 37
  • 1
    Probably initializes as true during a digest and changed later when it meets the required input. Just a speculation though. – Omri Aharon May 19 '15 at 16:25
  • @OmriAharon That is exactly what is happening, but why? Shouldn't it be invalid even at initialization time? – Carlos May 19 '15 at 17:22
  • I'd say that if it hasn't encountered the required input yet then it won't know it's invalid, since by then it's just an empty form. Would be nice though if I could get some confirmation though, haven't found this in any resource... – Omri Aharon May 19 '15 at 19:17

1 Answers1

5

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.

Okazari
  • 4,597
  • 1
  • 15
  • 27