Objectives and outcomes

In this tutorial we are going to learn about angular-js ngMessages module. We can link the module to our application using dependency injection. This module is used in form validation and it makes the task of displaying error very easy.

Image source: (https://docs.angularjs.org/api/ngMessages)

For ngMessages module to work we need to include angular-messages.js file in our application. We can link the file using four ways:

If you have downloaded angular package on localhost

<script src="angular-1.4.6/angular-messages.js"></script>

Using CDN

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-messages.js"></script>

Using npm

npm install angular-messages@1.4.6

Using bower

bower install angular-messages@1.4.6

HTML code:

<title>AngularJS Cookies</title>
<meta charset="utf-8">
<script src="angular-1.4.6/angular.min.js"></script>
<script src="angular-1.4.6/angular-messages.js"></script>
<div ng-app="message_app" ng-controller="message_control">
<form name="first" novalidate>
<label class="control-label">Username</label><br/>
<input type="text" required ng-model="user" name="username">
<div ng-messages="first.username.$error" role="alert">
<div ng-message="required">Please enter a value</div>
<form name="second" novalidate>
<label class="control-label">Email</label><br/>
<input type="email" required ng-model="email" name="email" maxlength="25">
<div ng-messages="second.email.$error" role="alert">
<div ng-messages-include="../angularjs/msg.html"></div>


<div ng-message="required">Please enter a value for this field.</div>
<div ng-message="email">This field must be a valid email address.</div>


var app = angular.module("message_app",['ngMessages']);
$scope.user = 'codeshot';
$scope.email = 'example@gmail.com';

Please enter a value

Above we have show two examples of using message functionality- one is using simple ng-message for each type of error and the other is using ng-messages-include method to include html file whicha has code defined for all errors. Therefore the second method is more suitable for large forms as we do not have to define error message again and again.
When a single form field has multiple error definition and $error flag is set for more than one field then the application does not display all error messages at the same time, it will display error according to the order of their definition.For example-:

<div ng-messages="formname.fieldname.$error" role="alert">
<div ng-message="required">Please enter a value for this field.</div>
<div ng-message="email">This field must be a valid email address.</div>
<div ng-message="maxlength">This field can be at most 15 characters long.</div>

Suppose if required and email both errors are active in above example then only required error will be shown because it comes above email error definition.