RVandersteen
RVandersteen

Reputation: 2137

Angular form validation using the controllerAs syntax

I am currently facing the following problem:

I would like to validate my form input using the Angular ngModel directives.

When using those together with $scope they work fine.
Now, working with the controllerAs syntax, they fail to work.

This problem is poorly documented, the only help I could find is this article.

Here is a small example of my code:

The template gets called with myController as vm

<form name="vm.signUpForm" ng-submit="vm.signup(vm.user)">

    <label for="name">Name</label>

      <input type="text"
                  class="form-control"
                  id="name"
                  name="name"
                  placeholder="Full name"
                  ng-model="vm.user.name"
                  ng-minlength="2" required />

    <div ng-show="vm.signUpForm.$submitted || vm.signUpForm.name.$touched">
        <span ng-show="vm.signUpForm.name.$error.required">Please fill in your name</span>
        <span ng-show="vm.signUpForm.name.$error.minlength">A minimum of 2 [...]</span>
    </div>

[...]
</form>

Am I forced to use $scope to validate the form? Or did I miss something ?

Thanks in advance!


Solution by: Andrew Gray

I had to change the following lines to get this to work:

<form name="vm.signUpForm" ... >
<!-- To -->
<form name="signUpForm" ...>


<div ng-show="vm.signUpForm.$submitted || vm.signUpForm.name.$touched">
<!-- To -->
<div ng-if="signUpForm.name.$invalid">

<span ng-show="vm.signUpForm.name.$error.required" ... >
<!-- To -->
<span ng-show="signUpForm.name.$error.required" ... >

Upvotes: 1

Views: 2758

Answers (1)

Andrew Gray
Andrew Gray

Reputation: 3790

First things first - you don't need the vm. on the form.

<form novalidate name="someForm">
    <label>
        Some Text:
        <span class="danger-text" ng-if="someForm.someText.$invalid">
           ERROR!
        </span>
    </label>
    <input type="text" name="someField" />
</form>

The way it winds up working, is that there's a validation object that is not tied to the scope. The controllerAs syntax is just spinning off a instance of the controller as a scope variable.

Try shaving off the vm. from the form and child elements' names, and you should be OK.

Upvotes: 4

Related Questions