Saturday 7 November 2015

A Few Tips on Gulp

I have been using Gulp a lot these days and have encountered a few cases that are a bit tricky to solve if you are new to Gulp. These scenarios get even trickier if you used Grunt before and just started using Gulp later, like myself. This is because, Grunt is synchronous and the execution of a Grunt task that combines a set of tasks is predictable. On the other hand, Gulp is asynchronous and we need to carefully examine the way a combined task runs in order to get maximum benefits out of it.

The asynchronous behavior of Gulp tasks makes it a bit difficult to perform things like chaining multiple tasks, handling tasks not returning a stream work seamlessly and performing multiple operations in a single task. In this post, we will see how to handle these tasks.

Chaining Multiple Tasks
It is common to define multiple tasks and combining them to create a master task. The master task alone is called whenever there is a need to perform the set of tasks together. Some of these tasks may be dependent on each other and others may be independent. In general, a set of Gulp tasks are combined using the following syntax:

gulp.task('build', ['copy-files', 'concat-files', 'run-tests', 'copy-coverage-results']);
Out of these tasks, the task concat-files is dependent on the task copy-files. The above setup starts executing these tasks at the same time. Execution of the task concat-files is not paused until execution of the task copy-files is completed. It can be solved in two ways. One way is to declare the task copy-files as a dependent task on the task concat-files and have the concat-files task alone as dependency on the build task.

gulp.task('concat-files', ['copy-files'], function(){
  //definition of the task

The second way is to run these tasks in sequence using the run-sequence package. It is shown below:

var runSequence = require('run-sequence');
gulp.task('copy-and-concat', function(){
  return runSequence('copy-files','concat-files');

We have to use one of these ways to solve this case based on the scenario in hand.

Task not returning a Stream
Sometimes we have to deal with tasks that don’t return streams. Such tasks are difficult to chain, as gulp doesn’t understand about their completion. One of such tasks is gulp-requirejs. We need to wrap execution of such tasks inside gulp pipes to make them return streams. Following snippet wraps the gulp-requirejs task inside a pipe:

  .pipe(requires(/*configuration of the task goes here*/))

Task handling Multiple Operations
A task may handle multiple asynchronous operations. In such case, the task has to return a stream representing the combined execution. Sometimes, we can return the stream returned by the last operation alone, but this approach doesn’t guarantee that all tasks are completed by the time the stream is completed. So, it is a good practice to combine such tasks using the event-stream package. Following snippet combines a number of copy operations into a single task using this package:

gulp.task('copy-files', function () {
  return es.merge(

I have encountered these cases quite a few times and the solutions discussed here worked well for me. These may not be the only possible ways to tackle these cases, but these are just my views. If you got any other ways to solve these problems, feel free to add a comment.

Happy coding!

Saturday 10 October 2015

Book Review - AngularJS by Example

I have just finished reading the book AngularJS by Example authored by Chandermani Arora. I will share my views on this book in this post.

A typical technology book starts with concepts on the technology and it continues to explain the technology throughout the book with independent examples. This book takes a different approach and start building an application right from beginning of the book. It continues adding features to the same example while explaining different concepts of the framework and covering internal details wherever needed.

Presentation of the entire book can be summarized into following the bullet points:

  • Starts with a brief discussion on problems with building large JavaScript applications. Explains need of patterns like MVC in the ecosystem
  • Doesn't build a regular "Hello World" sample, instead builds an interesting sample to cover basic constructs of the framework
  • Before building any step of the sample, the author spends time in explaining the problem, then tells which feature solves the problem and then explains the feature thoroughly before implementing the next step
  • Covers a number of tips through examples
  • Makes good use of the notes section to clarify some basics and lesser known facts
  • No concept is explained independently. Most of the necessary features of the framework are covered with right examples that are very close to real world problems
  • I particularly like the way some features like animations, ng-model, interceptors and testing are explained in the book
  • Last chapter focuses on a few common scenarios and provides advice containing best practices to solve these problems

This book doesn't just helps someone in gaining knowledge on AngularJS, but also teaches the needs of the features. Once you finish reading the book by following along with it and build the sample, you will have a self-built reference application that you can refer in the future.

The content in this book is relevant to both beginners and experienced developers working on AngularJS. A thorough read of this book will help you in mastering essential parts of the framework. You will also be able to answer most of the common interview questions once you read this book :).

Happy coding!

Friday 25 September 2015

Writing Gulpfile using TypeScript

Lately, I have been using Gulp a lot at my work and also in the demos of my articles. I also use TypeScript quite often these days while playing with Angular 2. While using Gulp to transpile TypeScript to JavaScript using Gulp, I got thought to use TypeScript itself to write the gulpfile as well. It might sound a bit weird as we use Gulp to transpile the files to JavaScript and the gulpfile itself has to be converted by someone into JavaScript before any other task runs. Thanks to npm scripts, we have a way to achieve this.

The scripts section of the package.json file can be used to register commands and these commands can be executed from command prompt of any OS using the “npm run” command. For instance, if we have the following configuration saved in scripts section of package.json file:

"scripts": {
  "setup" : "npm install && bower install"

We can run the command “npm run setup” from the command prompt. This command would install all Node.js dependencies and the bower dependencies. We can transpile the gulpfile using this section and then combine this command with a command to run a task. For this, we need to have TypeScript installed globally. This can be done using the following command:

> npm install –g typescript

To write the gulpfile using TypeScript and take advantage of the type checking system, we need to get the type definition files. Type definitions for the gulpfile are available on tsd. Following command gets the type definitions for the gulpfile:

> tsd install gulp --save

These files are saved inside typings folder of the project. To make our lives easier, the tsd command creates a type definition file that refers to all of the installed type definitions. This file is tsd.d.ts inside the typings folder.

Now, we need to refer the tsd.d.ts file in the gulpfile.ts file and start writing Gulp tasks. Following snippet shows a task that concatenates all JavaScript files:

/// <reference path="typings/tsd.d.ts" />

var gulp = require('gulp'),
    concat = require('gulp-concat');

gulp.task('default', function(){
  return gulp.src(["scripts/*.js"])

This example is a simple one. In more advanced scenarios, we can use types as well.

To run this gulp task, we need to define a command in the scripts section to transpile the file and then run the task. Following is the command:

"scripts": {
  "concat": "tsc gulpfile.ts && gulp"

All is done. We can now run this command as follows:

> npm run concat

Happy coding!

Tuesday 30 June 2015

Debugging and Profiling LINQ Queries using Devart LINQ Insight

Language Integrated Query (LINQ) is one of the features that makes .NET developers happy. LINQ opened up the opportunities to uniformly query in-memory objects, data in relational DBs, OData Services and many other data sources. Writing LINQ queries is fun as they reduce the usage of loops in code and keep the code base simple.

There are several ways to write LINQ queries to obtain a given result. As programmers, it is our responsibility to find the best way out of them and use that to make the applications perform better. Also, LINQ queries are hard to debug. It is not possible to debug a LINQ query using immediate window of Visual Studio debugging tools. So, we can’t say if a LINQ query is completely correct unless we write enough unit tests around it. Though unit tests are a good way to verify, nothing beats the ability of debugging the query by changing parameters.

LINQ Insight is a Visual Studio extension from Devart that makes debugging and profiling LINQ queries easier. It also provides profiling data for the LINQ queries and for CRUD operations performed using LINQ to in-memory objects as well as LINQ to remote objects (LINQ to SQL, Entity Framework, NHibernate and others). In this post, we will see a few of the features of this tool.

Debugging LINQ Queries
Once you installed LINQ Insight and restarted Visual Studio, you will see the options to see LINQ Interactive and LINQ Profiler windows under the View menu:

To debug the queries, we need to view the LINQ Interactive window. Select this option to view the window. Say, I have the following generic list of Persons in my application:
var people = new List<Person>() {
    new Person(){Id=1, Name="Ravi", Occupation="Software Professional", City="Hyderabad", Gender='M'},
    new Person(){Id=2, Name="Krishna", Occupation="Student", City="Bangalore", Gender='M'},
    new Person(){Id=3, Name="Suchitra", Occupation="Self Employed", City="Delhi", Gender='F'},
    new Person(){Id=4, Name="Kamesh", Occupation="Business", City="Kolkata", Gender='M'},
    new Person(){Id=5, Name="Rani", Occupation="Govt Employee", City="Hyderabad", Gender='F'}

Let’s write a LINQ query to fetch all males or, females from this list using a character parameter. Following is the query:
var gender = 'M';

var males = people.Where(p => p.Gender == gender).Select(p => new { Name=p.Name, Occupation=p.Occupation });

Right click on the query and choose the option “Run LINQ Query”. You will see this query in the LINQ Interactive window and its corresponding results.

As the query accepts a parameter, we can change value of the parameter and test behavior of the query. Hit the Edit Parameters button in the LINQ Interactive window and modify value of the parameters used in the query. On clicking OK, the query is executed and the result is refreshed.

Profiling Calls to Entity Framework
As most of you know, ORMs like Entity Framework convert LINQ Queries and function calls into SQL Queries and statements. The same result can be obtained using different types of queries. It is our responsibility to measure the execution time of all possible approaches of writing a query and choose the best one out of them.

For example, consider a database with two tables: Student and Marks.

The need is to find details of a student and the marks obtained by the student. It can be achieved in two ways. The first way is to find sum of the marks using navigation property on the student object and the other is to query the Marks DbSet using group by clause:
var studMarks1 = context.Students.Where(s => s.StudentId == studentid)
                        .Select(s => new
                            Name = s.Name,
                            Id = s.StudentId,
                            City = s.City,
                            TotalMarks = s.Marks.Sum(m => m.MarksAwarded),
                            OutOf = s.Marks.Sum(m => m.MaxMarks)

var studMarks2 = context.Marks.Where(m => m.StudentId == studentid)
                         .GroupBy(sm => sm.StudentId)
                         .Select(marksGroup => new
                             Name = marksGroup.FirstOrDefault().Student.Name,
                             Id = marksGroup.FirstOrDefault().Student.StudentId,
                             City = marksGroup.FirstOrDefault().Student.City,
                             TotalMarks = marksGroup.Sum(m => m.MarksAwarded),
                             OutOf = marksGroup.Sum(m => m.MarksAwarded)

Let’s see how much time does each of the above query takes using LINQ Profiler. Go to View menu and choose option to see the LINQ Profiler window. Now debug the application. After both of the queries are executed, visit the profiler window. You will see the data collected by the profiler. Following screenshot shows an instance of profiler’s data after running the above queries:

You can observe how much time each of these queries takes in different instances and with different values of the parameters before concluding that one of them is better than the other one.

As we saw, LINQ Insight adds a value add to the .NET developers. Devart has a number of other tools to help developers as well. Make sure to check them out and use them to make your development experience more enjoyable!

Happy coding!

Saturday 13 June 2015

Everything You Need to Know to Unit Test AngularJS Code

Unit testing is one of the crucial and necessary parts of software development. This phase improves the quality of product, assures accuracy in behavior and also reduces the cost involved in fixing the bugs. There are some good advantages for a developer writing unit tests as well.

AngularJS is one of the most popular framework for building Single Page Applications. One of the key reasons behind its success is, testability. Every piece of code written in AngularJS is unit testable. The features like Dependency Injection make the code written on the framework easier to test.

In the past, I wrote a few posts on unit testing AngularJS controller using Jasmine and QUnit and I also covered a few tips. Over past two years, I worked a lot on AngularJS and thus I wrote a lot of code and tests. This process taught me a lot of tips on unit testing AngularJS code that I wanted to share with the community. As some of you might be aware that I am a regular author for SitePoint, I have put together a series of four articles covering tips on mocking and testing almost every block in AngularJS. Following are the links to these articles:

  1. Mocking Dependencies in AngularJS Tests
  2. Unit Testing in AngularJS: Services, Controllers & Providers
  3. AngularJS Testing Tips: Testing Directives
  4. AngularJS Testing: Bootstrap Blocks, Routes, Events, and Animations

The process of putting these articles together has not been easy for me and at the same time, I enjoyed a lot while writing them. Read them when you get time and feel free to drop any feedback to me.

Happy coding!

Sunday 26 April 2015

Getting Started with Benchpress

Lately, most of us are quite busy with writing great front-end centric applications to make the look and feeling of our apps jazzy. Despite of the jazziness, the application won’t give a great experience to the user unless it performs really well on the browser. Performance of any piece of code can be improved only if we know that there is some scope for the improvement. Benchpress is one of the tools available to measure performance of AngularJS applications. In this post, we will see how to install benchpress and get started with using the data it provides us.

Benchpress is a performance measuring tool built on top of Protractor. It is built by the Angular team and is extensively used by them to measure performance of the framework. It is made available and can be used by anyone to measure performance of the Angular apps.

Installing Benchpress

Benchpress is an NPM package. So, it needs Node.js to be installed. As it uses protractor, you need to install protractor globally. Use the following command to install protractor:

npm install –g protractor

If you are installing it on a Windows machine, webdriver-manager may throw an error. To oversome this, you will have to update the webdriver-manager. Following command updates it:

webdriver-manager update

Restart the command prompt after this command completes execution.
Install protractor again after updating the webdriver-manager and it shouldn’t fail this time. You can find more details on installing protractor in its official documentation on GitHub.
Now that the system has protractor available as a global package, we can install benchpress. Benchpress also has to be installed globally. Following is the command:

npm install -g generator-benchpress

Getting a Glimpse of Benchpress ng-tasty
Now that we have all of the required setup, we can apply benchpress on a project. For this post, I will show the benchpress results using the yeoman scaffold of ng-tasty. I will explain the process of getting benchpress results on an existing piece of code in a future article. As we need to install a yeoman scaffold, you must have yeoman installed. If you don’t already have, run the following command to install it:

npm install –g yo

Create a new folder at your desired location and install the following NPM packages locally:
  • http-server
  • benchpress

Benchpress needs these packages to start the Node.js HTTP server and run the scenarios tests. The final thing that we need to get is, the yeoman scaffold. Run the following command in the same folder where the above NPM packages are installed: yo benchpress ng-tasty

This scaffold adds a folder called benchmarks and inside this folder and the folder has following content:
  • protractorBenchmarks.conf.js: It is the configuration file for benchpress. It contains the browser details, spec files to run, test framework to use, the task to be performed before launching benchpress and a config object for jasmine
  • index.html: This file is inside the ng-tasty folder and it is the page to be inspected on
  • benchmark.spec.js: This file is inside the ng-tasty folder. The spec file that uses Selenium web driver to perform operations on the page
Now, we have everything to run benchpress and see some results. Run the following command on the console and see the outcome:

protractor benchmarks\protractorBenchmarks.conf.js

This command starts Selenium Web Driver and loads the index.html on Chrome. It performs the set of operations configured and prints results on the console.

Happy coding!

Wednesday 7 January 2015

Private Members in ES6 Classes

Classes in ECMAScript 6 are easy to write and use. Yet, they have certain limitations. One of them is, there is no direct way to create a private member inside the class.

The classes don’t allow us to declare variables directly inside body of the class. All members defined/declared inside the class or attached to an instance using this keyword are directly available to the instance of the class.

When I Googled it, I found a few posts on it and answers suggesting to use Symbol. I think, Symbol was private sometime back but according to the current draft of ES6, properties created using Symbol values are not private anymore. Though value of Symbol can't be reproducible, one can read Symbol properties using Object.getOwnPropertySymbols.

For example, consider the following class and object:

const ID = Symbol();
class Employee{
  constructor(id, name){ = name;
    this[ID] = id;
var emp = new Employee(1001, "Ravi");

Though value of id is not accessible using emp[Symbol()], as it returns a different Symbol, we can extract all Symbols used for properties and values of these properties as:

var symbolsInEmp = Object.getOwnPropertySymbols(emp);

The above snippet will print value of id stored in the object emp. If there are multiple Symbol properties, you may not be able to find which value corresponds to what value, but the data is not private.

To make a value private, we can do one of the following:

  • set and use the value inside a closure
  • create the variable inside a module and not export it

WeakMap seems to be a good option for creating the private fields. Because, it accepts any value as key and it doesn’t prevent the key object from getting garbage collected when the WeakMap object still exists. It removes entry containing the object once it is garbage collected. For each private field, we need to create a new WeakMap object.

Following snippet shows how WeakMaps can be used as private fields:

const ID = new WeakMap();
const PAN = new WeakMap();

class Employee{
  constructor(id, name, pan){ = name;
    ID.set(this, id);
    PAN.set(this, pan);
    return PAN.get(this);
var emp = new Employee(1001, "Ravi", "FFHH1919JJ");

export default Employee;

As you see, we are exporting the Employee class alone from the module. Here, the classes don't contain the fields themselves, but they are relying on the private objects of the module to keep the data private.

Happy Coding!

Thursday 1 January 2015

Static Class Members in ES6

I have been playing with ECMAScript 6 for some time now and I must say that the new features added in this edition are worth taking a look. One of the significant language feature added in this specification is, support for classes. If you are not aware of the features of ES6, checkout the specification on official site for ECMA Script or, the un-official HTML version of the specification on Mozilla’s site.

ES6 classes support most of the features like creating object, constructor, inheritance and overriding that are supported by Object Oriented programming languages like C# or Java. And because it is JavaScript, there is no static type checking.

I found it interesting when I saw the support for static members in the specification. The specification says, we can add a static method to a class using the following syntax:

static methodName(){

But, if you attempt to declare a static property as follows:

static propertyName;

It results in an error. So, we can’t declare a static property. But, we can create it inside a method and use it. To access a static member inside a static method, we need to use this keyword. Because, this reference in JavaScript refers to the object using which the method is invoked. Static methods are called using name of the class to which they belong and name of the class in JavaScript refers an object that has a prototype property containing instance members of the class. For example, consider the following class:

class Employee
  constructor(){ = "Ravi";
  setName(name){ = name;

The above code is similar to:

function Employee(){"Ravi";
Employee.prototype = {
  setName: function(name){;

Here Employee is name of the class and at the same time, it is also an object. All static members of the Employee class are attached to the Employee object.

Let’s add a static method to the Employee class:

class Employee
  constructor(){ = "Ravi";
  setName(name){ = name;

  static getCounter(){
    if(!this.counter && this.counter!==0){
    return this.counter;

The property counter used in the getCounter method of the above snippet becomes a static property, as it is assigned to this reference inside a static method. Similarly, another static method of the class can be called from a static method using this reference.

The following console.log statements will print the results specified in the comments:

console.log(Employee.getCounter());  //0
console.log(Employee.counter);       //0
console.log(Employee.getCounter());  //1
console.log(Employee.counter);       //1
console.log(Employee.getCounter());  //2
console.log(Employee.counter);       //2

Happy Coding!

Thursday 25 December 2014

Automating Tasks in Front-end Web Apps Using Gulp

As we started writing a lot of JavaScript and CSS these days, front-end development has matured like anything. We create hundreds of JavaScript source files to make our code organized; but finally we need to ship just one JavaScript file and one CSS file while deploying the application. This conversion is not easy; as it involves several steps like running tests, validating against jshint, concatenating, minifying, uglifying and many other tasks. Thankfully, we have a number of automated task runners and a handful of plugins on each of these task runners to make these tasks easier.

Out of the existing task runners, Grunt and Gulp are most widely used. I use Grunt a lot these days. Though I haven’t blogged about it, I used it in some of my SitePoint articles. Lately, Gulp is becoming more famous. Gulp uses a different approach to address the same problem that Grunt addresses. Let’s see how we can leverage Gulp to automate our tasks.

Gulp is a task runner based on Node.js. It uses streams to carry its tasks. The way Gulp works is, it accepts a source (can be a file, or a set of files), processes them based on a task and passes it to the next task in the pipe for further processing. The pipes continues processing till the last task. Following is the syntax of a typical Gulp task:

gulp.task('task-name', function () {
  return gulp.src([source paths])

Tasks piped in the above Gulp task are tasks loaded using Gulp plugins. Gulp has a huge number of plugins contributed and actively developed by community, which makes it a very good ecosystem. To be able to use Gulp in your project, you need to have it installed globally and locally. Run the following commands in a command prompt to get Gulp installed:

  • npm installed –g gulp
  • npm installed gulp --save-dev (To be ran in your project folder)

Let’s write a Gulp task for cleaning distribution files and regenerating them after concatenating and minifying. For this, we need the following Gulp plugins:

  • gulp-clean
  • gulp-concat
  • gulp-uglify

These can be installed using the following nom commands:
  • npm install gulp-clean --save-dev
  • npm install gulp-concat --save-dev
  • npm install gulp-uglify --save-dev

Add a file to the project and rename it to Gulpfile.js. Load the Gulp tasks in this file:

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    clean = require('gulp-clean');

Before generating the files to be deployed, let’s clean the folder. Following task does this:

gulp.task('clean', function () {
    return gulp.src(['dist'])

Now, let’s create a bundle task that concatenates all JS files, uglifies them and copies inside a folder to be distributed. Following is the task:

gulp.task('bundle', function () {
  return gulp.src(['public/src/*.js'])

The folder public/src contains all JS files of the application. They are concatenated into one file and the contents are then uglified and finally we call the dest task to copy the resultant file to destination, which is the dist folder.

These two tasks can be combined into one task as follows:

gulp.task('createDist', ['clean', 'bundle']);

Now, if you run the following command, you will have the combined.js file created inside dist folder.

gulp createDist

To make a task default, name of the task has to be default.

gulp.task('default', ['clean', 'bundle']);

To run this task, you can run gulp command without passing names of any tasks to it.

We will see explore more features of Gulp in future posts.

Happy coding!

Monday 27 October 2014

Form Validation and Displaying Error Messages using ngMessages in AngularJS 1.3

AngularJS 1.3 was released around two weeks back. As the core Angular team says, it is the best AngularJS released till date. It comes with a bunch of new features and performance improvements.

One of the key changes in this release is the changes made to forms. The directives form and ngModel went through a number of changes to make it easier to perform validation. The framework has a new module, ngMessages that makes the job of displaying validation messages easier.

In the current release, FormController have following additional APIs:

  • $setUntouched(): A method that sets all controls in the form to untouched. It is good to call this method along with $setPristine()
  • $setSubmitted(): A method that sets the state of the form to submitted
  • $submitted: A boolean property that indicates if the form is submitted

NgModelController has the following additional APIs:

  • $setUntouched(): A method that sets the control to untouched state
  • $setTouched(): A method that sets the control to touched state
  • $validators: A list of synchronous validators that are executed when $validate method is called
  • $asyncValidators: A list of asynchronous validators that are executed when $validate method is called
  • $validate(): A method that executes all validators applied on the control. It calls all synchronous validators followed by asynchronous validators
  • $touched: Boolean property that indicates if the control is touched. It is automatically set to true as soon as cursor moves into the control
  • $untouched: Boolean property that indicates if the control is untouched

For more details on these APIs, read the official API documentation of FormController and NgModelController.

Let’s see these APIs and the new featured in action. Consider the following form:

<form name='vm.inputForm' ng-submit='vm.saveNewItem()' novalidate>
  Item Name: <input name='itemName' type="text" ng-model='' required non-existing-name />
  <br />
  Min Price: <input name='minPrice' type="text" ng-model='vm.newItem.minPrice' required ng-pattern='vm.numberPattern' />
  <br />
  Max Price: <input name='maxPrice' type="text" ng-model='vm.newItem.maxPrice' required ng-pattern='vm.numberPattern' greater-than='vm.newItem.minPrice' />
  <br />
  Quantity Arrived: <input name='quantity' type="text" ng-model='vm.newItem.quantity' ng-pattern='vm.numberPattern' />
  <br />

  <input type="submit" value="Save Item" />

Note: Notice name of the form in the above snippet. It is not the way we usually name the HTML elements. We assigned a property of an object instead of a plain string name. Reason for using this is to make the form available in the controller instance. This approach is very useful in case of controllerAs syntax. (Credits: Josh Caroll’s blog post)

The form has some built-in validation and two custom validations. Built-in validations work the same way as they used to in the earlier versions ( Refer to my old blog post that talks a lot about the validations). We will write the custom validations in a minute.

Following is the controller of the page. As stated above, I am using “controller as” syntax, so no $scope in the controller.

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

app.controller('SampleCtrl', function(){
  var vm = this;

  vm.inputForm = {};

  vm.numberPattern = /^\d*$/;

  vm.saveNewItem = function(){

Custom Synchronous Validations

The process of defining custom validations has been simplified in AngularJS 1.3 with $validators and $asyncValidators. We don’t need to deal anymore with $setValidity() to set validity of the control.

In case of synchronous validations, we need to return a boolean value from the validator function. The validation is passed when result of the validator function is true; otherwise, it fails.

In the form, we are accepting min price and max price values. The form should validate that the value of min price is always less than value of max price. Following is the directive for this validation:

app.directive('greaterThan', function(){
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl){
      ngModelCtrl.$validators.greaterThan= function(value){
          return parseInt(value) >= parseInt(scope.greaterThanNumber);

      scope.$watch('greaterThanNumber', function(){

If the above validation fails, it sets invalid flag to greaterThan validation on the control. Name of the method set to $validators is used as the validator string.

Custom Asynchronous Validations

In some scenarios, we may have to query a REST API to check for validity of data. As AJAX calls happen asynchronously, the validator function has to deal with promises to perform the task.

For the demo, I created a dummy asynchronous method inside a factory that checks for existence of the new item name in a static array and resolves a promise with a boolean value. Following is the service:

app.factory('itemsDataSvc', ['$q',function($q){
  var itemNames=['Soap', 'Shampoo', 'Perfume', 'Nail Cutter'];

  var factory={};

    var nameExists = false;
      if(itemName === name){
    return $q.when(nameExists);

  return factory;

The difference between synchronous and asynchronous validators is the API used to resister the validator and the return value of the validator method. As already stated, $asyncValidators of NgModelController is used to register the validator and the validator method has to return a promise. The validation passes when promise is resolved and the validation fails if the promise is rejected.

Following is the custom asynchronous validator that checks for unique name:

app.directive('nonExistingName', ['itemsDataSvc','$q',function(itemsDataSvc, $q){
  return {
    link: function(scope, elem, attrs, ngModelCtrl){
      ngModelCtrl.$asyncValidators.nonExistingName = function(value){
        var deferred = $q.defer();


        return deferred.promise;

Validation Error Messages using ngMessages

Displaying validation messages of the form in AngularJS had not been too good earlier. It used to take a lot of mark-up and conditions to make them look user-friendly. AngularJS 1.3 has a new module, ngMessages that simplifies this task. If you refer to the module definition statement in the controller script, it has a dependency on ngMessages module. This module doesn’t come by default as part of the core framework, we have a separate file for this module.

The ngMessage module contains two directives that help in showing messages:

  • ngMessages: Shows or hides messages out of a list of messages
  • ngMessage: Shows or hides a single message

The directives in ngMessages module support animations as well. I will cover that in a future post.

In case of displaying form validation messages, ngMessages is set to the $error property of the form object and every occurrence of ngMessage element is set to the condition for which the message is has to be displayed.

<div ng-if='vm.inputForm.$dirty &amp;&amp; vm.inputForm.$invalid' ng-messages='vm.inputForm.$error' class='error-messages'>
  <div ng-message='required'>One/more mandatory fields are missing values</div>
  <div ng-message='pattern'>Data is in incorrect format</div>
  <div ng-message='greaterThan'>Invalid range</div>
  <div ng-message='nonExistingName'>Name already exists</div>

By default, ngMessages displays the first message out of the list even if more than one message is relevant. It can b overridden using multiple or ng-messages-multiple attribute on the ngMessages directive.

The above message list is generic to the form; the messages are not specific to any of the control in the form. To display messages specific to form, you can use the $error property on the form element.

<div ng-if='vm.inputForm.itemName.$dirty' ng-messages='vm.inputForm.itemName.$error' class='error-messages'>
  <div ng-message='required'>One/more mandatory fields are missing values</div>
  <div ng-message='nonExistingName'>Name already exists</div>

You can play with the sample on Plnkr.

Happy coding!