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">

And also a controller:

angular.module('sample', []).controller('MainController', function($scope) {
  $scope.$watch('form.$valid', function (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


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.

Answered By – Okazari

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.