Categories: Javascript

AngularJS Coding Best Practices

The article lists down some of the best practices that would be useful for developers while they are coding with AngularJS. These are out of my own experiences while working on AngularJS and do not warranty the entire list. I am sure there can be more to this list and thus, request my readers to suggest/comment such that they could be added to the list below. Found some of the following pages which presents a set of good practices you would want to refer. Thanks to the readers for the valuable contribution.

 

Initialization
  • One should try and place the <script> tag including the angular.js and related angular scripts at the bottom of the page to improve the app load time. This is because the HTML loading would then not be blocked by loading of angular.js and related scripts.

 

Expressions
  • Complex javascript code should be made as a method in the controller (added as a method to the $scope) and then, should be called from the view. This is unlike putting the complex Javascript code as Angular expressions, right, in the view.

 

Controllers
  • With real applications, one should avoid creating controllers in the global scope. Rather, one should use “.controller” method of the Angular Module to work with $scope object. Take a look at the sample code below illustrating this point:

Controller defined in the Global Scope:

function HelloController( $scope ) {
$scope.name = "Guest";
}

Controller defined using “.controller” method (Recommended way)

var helloApp = angular.module( "helloApp", [] );
helloApp.controller( "HelloController", function($scope){
$scope.name = "Guest";
} );

 

  • The controllers should only be used to setup initial state of the $scope object and add one or more behaviour to this object. One should avoid using controllers to do some of the following:
    • Manipulate DOM,
    • Format input,
    • Filter output,
    • Share code or state across different controllers
    • Manage the life-cycle of other components (for example, to create service instances)
  • A controller should contain only the business logic needed for a single view. The functionality should rather be moved to services and these services should be injected into the controllers using dependency injection.
  • The recommended way to declare the controller function is to use the array notation such as following because it protects against minification.

Controller instantiation without array notation

var helloApp = angular.module( "helloApp", [] );
helloApp.controller( "HelloController", function($scope){
$scope.name = "Guest";
} );

Controller instantiation with array notation (Recommended way)

var helloApp = angular.module( "helloApp", [] );
helloApp.controller( "HelloController", ['$scope', function($scope){
$scope.name = "Guest";
}]);

 

  • While writing unit tests for controllers, one of the recommended ways is to inject $rootScope & $controller. Take a look at the sample unit tests on this page: http://hello-angularjs.appspot.com/angularjs-unit-test-code-example-1. Following is the sample code representing injection of $rootScope and $controller objects.
    beforeEach(
     inject(
      function( $rootScope, $controller ){  
       scopeMock = $rootScope.$new();  
       $controller( 'CompanyCtrl', {$scope: scopeMock} );
      }     
     )
    );
Directives
  • One should prefer using the dash-delimited format (e.g. ng-model for ngModel). While working with an HTML validating tool, one could instead use the data-prefixed version (e.g. data-ng-model for ngModel).
  • Prefer using directives via tag name and attributes over comment and class names. Doing so generally makes it easier to determine what directives a given element matches.
  • While creating directives, it is recommended to prefix your own directive names to avoid collisions with future standard.

 

Template
  • With large templates (HTML content with Angular directives) within an HTML file, it is recommended to break it apart into its own HTML file and load it with the templateUrl option.

 

Dependency Injection

The preferred way of injecting the dependencies is by passing the dependency to the constructor function rather than using one of the following other ways. In this way, the responsibility of creating the dependency object lies with other objects or function. This is straight forward for those who have worked with one or more dependency injection framework in the past. However, this could be useful information for the beginners. Following are other ways of doing dependency injection in Angular:

  • Create it using the new operator.
  • Look for it in a well-known place, also known as a global singleton.
  • Ask a registry (also known as service registry) for it.

 

Unit Testing
  • As mentioned above, one should try and avoid using controller methods for DOM manipulation. That would bring views code inside the methods and make it difficult to test.
  • One may want to use Jasmine/Karma combination for doing controller methods testing.
  • Protractor framework can be used for E2E testing, as recommended. Read more on Angular page for E2E testing.

[adsenseyu1]

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

View Comments

  • One thing to keep in mind... The script tag's "async" and "defer" attributes can help with the loading issues.

Share
Published by
Ajitesh Kumar

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

2 months ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

2 months ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

3 months ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

3 months ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

3 months ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

3 months ago