1

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" ... >
2
  • submitted is defined in controller? Commented Mar 30, 2015 at 16:36
  • It isn't, how should i define this ? Is this one of the properties that come with the scope variable ? Commented Mar 30, 2015 at 16:40

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.