Best Practices Used in AngularJS

There are various components in the AngularJs such as Services, Views, Directives, Controller and Modules and so on. First let us summarize what these components do.

Angular Js
When developing an Angular application we must keep in mind these preceding components and what their roles are exactly. Understand the framework and lifecycle clearly for each component.

The following are the best practices that we should follow.

Use dependency Injection

In AngularJs the module depends on multiple dependent components, such as services, values, config and so on. This is to adhere to dependency injection in AngularJs that helps us in providing an instance of the dependent component for a loosely-coupled solution. In an Angular code when defining dependencies, inject the dependent components by its name using square bracket [] notation for listing your dependencies along with the functions.

AngularJs has a built-in dependency injector that tracks all components (services, values and so on) and returns instances of necessary components using dependency injection. The AngularJs dependency injector works based on the names of the components.

The following is a simple case of dependency injection:

  1. fundTransferModule.controller("fundTransferController", function($scope, $window, fundTransferService){  
  2.   
  3. });  

Here, $scope, $window and fundTransferService are passed into the controller using dependency injection, but the preceding code will break when the code is minified. The following approach solves that:

  1. fundTransferModule.controller ("fundTransferController ", ["$scope""$window"" fundTransferService ",  
  2.   
  3. function($scope, $window, fundTransferService){  
  4.   
  5. }]);  

Manage packages with bower components

When we are referring to any external script as a reference then it should be managed by bower components as in the following:

bower install – <component Name>

bower.json

  1. dependencies:  
  2. {  
  3.   
  4.    "angular-strap":"2.0.0.0",    
  5.    "restangular":    
  6.    "ProjectName/project#"  
  7.   
  8. }  

By doing this we follow:

  • Consistent and no manual download,
  • No local changes,
  • Upgrade the dependencies easily.

Use directives when there is need for common functionality

 Directives are a good feature in AngularJs that gives the reusability concerns.

 

  • Directives are used for reusable purposes such as the Date Picker control, File Uploader control and any type of custom validation or custom logic to a control that can be used across the application on any page. It is a component such as a user control in ASP.NET web pages or HTML Extensions in ASP.NET MVC applications.
  • Don't do DOM manipulation in controllers or services. Do not access the DOM outside of a directive because it decouples the controller and the services from the DOM. Therfore it is more flexible and is easier to test and can be reused.
  • Design the directive not to use controller scope, the directive should work independently of the scope or controller if it is designed for reusability purposes.
  • Don't write any custom directive with the name starting with ng-, it may conflict with an Angular built-in directive.

 Use Scope properly

 

  • Scope to be considered a data container for Angular applications. Use scope only when you need to pass data between the view and controller or model.
  • Do not store DOM elements in the scope because you can create huge memory leaks.
  • Angular constantly checks the "dirty check" to see if anything changed in the scope.
  • The content that is necessary by UI put on scope.
  • Just put exactly what will be displayed on the UI on the scope and leave the rest as variables in the controller, but not on the scope.
  • Every item added to scope adds a $watch to the item that listens for changes and updates/renders them between the controller and view.

Organize the file and folder structure properly

Use proper naming conventions for various types of files using prefixes such as mdl, fltr, srv cnst, .val, mock, dirct for module, filter, service, constant, value, mockdata and directive respectively. It will be easier to identify which type of JavaScript file it is, whether a directive or a controller or a service .

Organize your folders depending on your project needs, create various folders for Controller, directive, services and put its dependent file in the same folder. If possible put only 1 component in each file.

In case of a large application, create a different module.

The following is an example of a folder structure: 

 
 
Namespacing components

Provide a proper namespace for the components. Proper namespace avoids namespace collision and prevents duplicate naming.

Assume we integrate a third-party plugin with the same name such as app.js or main.js or default.js that is already defined in the project. This integration may create ambiguity issues to refer to which file. So it is recommended to use a namespace like the following:

  1. app. controller ("myApp.core.mainctrl",[])// myApp.core.mainctrl is the namespace here.  

Write unit testing

Write unit testing to the codes from the very beginning of the development. Unit testing gives advantages of better testing and faster bug tracking .ng-mock service is given by AngularJs to do mocking to various components. Use Jasmine or Karma for unit testing.

Use promises for service calls

AngularJs promises are an extremely powerful tool. They allow you to make a multi-layered and complex system based on asynchronous functions, with error and in-progress notification handling, all without getting into callbacks such as a success call or a failure call. AngularJs has exposed the “$q” service for it. A number of AngularJs services return promises, including $http, $interval and $timeout.

Avoid global variables

Avoiding global variables is very important because as a Single Page App, the Garbage Collector will never be triggered to clear out global variables.

Put Script at the bottom of the Page

When referring to the external scripts, such as controllers, services and modules, put them at the bottom of the page. Putting them at the bottom of the page will allow the page to not wait until the script loads.

Avoid using watch in scope

AngularJs has good performance out of the box. Because of the dirty checking done in a digest cycle, once the number of watchers exceeds 2,000, the cycle can cause noticeable performance issues. When designing a Single Page Application, avoid using watch function calls in scope from your code.

Use the scope effectively

 

  • Assignment of data to scope must happen in controllers and the service will be the provider to the controller. That data will be assigned to the view from scope.
  • Follow the scope inheritance effectively, understand the requirements properly from which the scope data must come, either the parent scope, isolated scope or root scope.
  • Use Scope.Apply() explicitly when there is a need for calling the scope $digest cycle explicitly. For example, if you have a custom directive that sets up a DOM event listener and changes some models inside the handler function, you need to call $apply() to ensure the changes take effect.

 These were some of the best practices in AngularJs. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all