1

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?

2 Answers 2

1

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

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

Comments

0

add var at the start

var app = angular.module('app', []);

app.controller('NewUserController', function($scope) {

check updated plunker

1 Comment

did the answer helped?

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.