Learn AngularJS Modules and Best Practices

What is AngularJS module?

AngularJS modules are a logical separation between the controllers, services, filters, directives etc. In simple words, a module is a container for the different parts of the application. AngularJS framework is popular because it supports the modular approach. By using modular framework we can keep the code base neat and clean.

Advantages of AngularJS Modules

  1. The architecture will be loosely coupled
  2. The declarative process will be easy to understand.
  3. You could package code as reusable modules, it means you can be plug and play the modules into different applications.
  4. Easy to maintain the code.
  5. Unit tests have to load only relevant modules which help in speed up the process.
  6. Modules can be loaded in parallel or in any order.

AngularJS Modules Best Practices to be followed

  1. Create different modules for each feature.
  2. Create modules for every reusable component.
  3. Add an application level module which contains initialization code for all the above modules.

Creating an Application module in AngularJS

We can create the module by using the angular method angular.module("moduleName",["dependency1","dependency2"]).The above code is a syntax of declaring the angular module, “myFirstApp” is the name of the module and you can pass the dependencies of the module in the next parameter as an array.

Now we have declared a module we can go head and create the controller, directives, filters etc.

Creating an Controller Module in AngularJS

We now have created an application module and controller module let’s see how we integrate both the things in HTML.

Angularjs modules Example

Modules should always be separated into different files so that we can reuse it. So you separate the application module and controller module into 2 different files for better code maintainability.

AngularJS Modules split into separate JS files



You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.