Search code examples
angularjsng-classstrict

Angularjs: ng-class and form validation


I am a newer angular user and i trying to do validation over a form. I found an example here: http://plnkr.co/edit/gLDFaf?p=preview

It's exactly what i want...so what my problem :) I don't understand why validation (red border) doesn't work if i add "use strict"; at the top of script.js

"use strict";  // <-- validation doesn't work if removed
module = angular.module('app', []);

module.controller('NewUserController', function($scope) {
  $scope.save = function() {
    if ($scope.userForm.$valid) {
      alert('User saved');
      $scope.reset();
    } else {
      alert("There are invalid fields");
    }
  };

  $scope.reset = function() {
    $scope.user = { name: '', email: '' };
  }
});

And the view:

 <body ng-app="app" ng-controller="NewUserController">
    <h1>Add New User</h1>
    <form name="userForm" novalidate>
      <div class="form-group" ng-class="{ 'has-error': userForm.name.$invalid }" >
        <label class="control-label">Name</label>
        <input type="text" class="form-control" name="name" ng-model="user.name" required placeholder="Name" />
      </div>
      <div class="form-group" ng-class="{ 'has-error': userForm.email.$invalid }" >
        <label class="control-label">Email</label>
        <input type="email" class="form-control" name="email" ng-model="user.email" required placeholder="Email" />
      </div>
      <button class="btn btn-primary" ng-click="save()">Add User</button>
      <button class="btn btn-link" ng-click="reset()">Reset</button>
    </form>
  </body>

Can someone explain this?


Solution

  • If you have a look at your browser's console, you'll see that the JS code actually crashes and therefore none of your JS code is active; so there is no Angular validation and the form just submits itself in a standard HTML behavior.

    The reason your JS crashes is because you can't create global variables in strict mode. Your module variable is declared without a var statement, which would normally make it a global variable. Adding a var statement makes your code work.

    "use strict";
    var module = angular.module('app', []); // The variable is properly defined
    

    You can find more information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Converting_mistakes_into_errors