AngularJs Best Practices

Published Jul 10, 2017
AngularJs Best Practices

When developing an application using a particular framework/library you need to know about it's best practices and style to create a clean and concise code.

These are based on my experience working in a team and https://docs.angularjs.org/guide. You can use these practices any where but some are more specific to angularjs like 'Manual Annotation for dependency injection'

Small & Pure Functions

Use small functions because they are easy to test and maintain. Pure functions are which return output depending upon some input. These functions don't change input in any way and only job is to produce an output.

// Pure function
function add (a, b) {
  return a + b;
}
// Not pure function
function add (a, b) {
  var x = a + b;
    console.log(x); // Doing other job than returning output
    return x;
}

Modules and Single Responsibility

Divide your code in seperate modules and every modules should be responsible for a single functionality. This increase usability.
For example you are building a mailing application like gmail. You divide functionality in three pieces (filters, search bar and email listing). When you develop modules based on single responsibility then you can easily manage and test your code.

use controllerAs syntax

When using controller anywhere in your angularJs application try using controller as syntax.

<div ng-controller="userController as user">
  {{ user.name }}
</div>

This is more contexual, easier to read, and avoids using other than dotted object in view like {{ name }} instead of {{ user.name }}.

Thin Controllers

Use controller only to make specific data available for scope which is being used in view. Use business and other logic in services;
When doing so these logic can be used in multiple controller and can be easily tested.
This removes dependencies and hide implementation from controller

//avoid
angular.module('app').controller(function ($http, $q) { 
  let _this = this;
  this.userDetails = {};
  this.getUserDetails = function () {
    	return $http.get(_url)
        	.then(function (data) {
            	_this.userDetails = data;
            }).catch(function (erro)) {
            });
    };
});

//recommended
angular.module('app').controller(function (userService) { 
  let _this = this;
  this.userDetails = {};
  this.getUserDetails = function () {
    	return userService.getUserDetail()
        	.then(function (data) {
            	_this.userDetails = data;
            }).catch();
    };
});

In above example getting data from server is delegated to service and our controller doesn't need to inject $http, $q and other dependencies. Use services for business logic.

Use controller for a single view for better testing and maintenance.

Return promises from Data Calls

When using services and doing data calls from there. Then try to return promises. This way user can chain the promises and take further action after the call is either rejected or resolved.

Directives only for DOM maninpulation

Use Directives only for Dom Maninpulations. When you think you aren't using compile/link function in directives then use only components. Components are available after angularJs 1.5.
And also when creating directives use restrict: 'EA'.

Manually identify Dependencies

When you try to minify angularjs code then it's a great help.

//avoid
angular.module('app').controller(function ($http, $q) { 
});

This would be minified to

angular.module('app').controller(function(a,b){});

and would break the code. Instead try like this;

angular.module('app').controller(['$http', '$q', function ($http, $q) { 
}]);
//minified
angular.module('app').controller(['$http',$q',function(a,b){}]);

Exception Cathers

Create a factory that exposes interface to catch and handle erorrs/exceptions.
Use $routeChangeError to handle routing errors and redirecting user to a valid error screen.

I hope you find this helpful. I would try to be more detailed with code and example in future.

Discover and read more posts from Faizan Haider
get started
Enjoy this post?

Leave a like and comment for Faizan

4