Dot Net Stuff

Using Modules to Organize Code in Angular JS


Till now we have learn about how AngularJS uses dependency injection with factory functions when you create components such as controllers, filters, and services. We also know that the second argument to the angular.module method, used to create modules, was an array of the module’s dependencies

...
var myApp = angular.module("exampleApp", []);
...

Any AngularJS module can rely on components defined in other modules, and this is a feature that makes it easier to organize the code in a complex application. To demonstrate how this works, we have added a JavaScript file called controllers.js to the angularjs folder. Following example code given-.

The Contents of the controller.js File

var controllersModule = angular.module("exampleApp.Controllers", [])
controllersModule.controller("dayCtrl", function ($scope, days) {
$scope.day = days.today;
});
controllersModule.controller("tomorrowCtrl", function ($scope, days) {
$scope.day = days.tomorrow;
});

In the controllers.js file we created a new module called exampleApp.Controllers and used it to define the two controllers from earlier examples. One common convention is to organize your application into modules that have the same type of component and to make it clear which building block a module contains by using the main module’s name and appending the block type, which is why it’s called exampleApp.Controllers. Similarly, we have created a second JavaScript file called filters.js, the contents of which are shown in below example code.

The Contents of the filters.js File

angular.module("exampleApp.Filters", []).filter("dayName", function () {
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
return function (input) {
return angular.isNumber(input) ? dayNames[input] : input;
};
});

We have created a module called exampleApp.Filters and used it to create the filter that was part of the main module in earlier examples. For variety, we have used the fluent API to call the filter method directly on the result of the module method.

There is no requirement to put modules in their own files or to organize modules based on the building blocks they contain, but it is the approach and generally prefer and is a good place to start while you are figuring out your own AngularJS development processes and preferences. In following example, you can see how we have added script elements to import the controllers.js and filters.js files and added the modules they contain as dependencies to the main exampleApp module. We have also created two further modules within the example.html file to emphasize that modules don’t have to be defined in their own files.

Using Module Dependencies in the example.html File

<!DOCTYPE html>


AngularJS Demo







<body>

Today is {{day || "(unknown)" | dayName}}

Tomorrow is {{day || "(unknown)" | dayName}}

</body> </html>

To declare the dependencies for the main module, add each module’s name to the array we will pass as the second argument to the module, like this:

...
var myApp = angular.module("exampleApp", ["exampleApp.Controllers", "exampleApp.Filters",
"exampleApp.Services", "exampleApp.Directives"]);
...

The dependencies don’t have to be defined in any particular order, and we can define modules in any order as well. For example, We have define the exampleApp.Services module in the above example code after we have defined the exampleApp module that depends on it.

AngularJS loads all the modules that are defined in an application and then resolves the dependencies, merging the building blocks that each contains. This merging is important because it allows for the seamless use of functionality from other modules. As an example, the days service in the exampleApp.Services module depends on the nowValue value in the exampleApp module, and the directive in the exampleApp.Directives module relies on the filter from the exampleApp.Filters module.

We can put as much or as little functionality in other modules as you like. We have defined four modules in this example but left the value in the main module. We could have created a module just for values, a module that combined services and values, or a module with any other combination that suited my development style.

Working with the Module Life Cycle

The Module.config and Module.run methods register functions that are invoked at key moments in the life cycle of an AngularJS app. A function passed to the config method is invoked when the current module has been loaded, and a function passed to the run method is invoked when all modules have been loaded. See an example of both methods in use, given below.

Using the config and run Methods in the example.html File

...

...

Our first change in this above code is to use the constant method, which is similar to the value method but creates a service that can be declared as a dependency by the config method (which we can’t do when you create values).

  • The config method accepts a function that is invoked after the module on which the method is called is loaded.
  • The config method is used to configure a module, usually by injecting values that have been obtained from the server, such as connection details or user credentials.
  • The run method also accepts a function, but it will be invoked only when all of the modules have been loaded and their dependencies have been resolved. Here is the sequence in which the callback functions are invoked:
    1. The config callback on the exampleApp.Services module
    2. The config callback on the exampleApp module
    3. The run callback on the exampleApp.Services module
    4. The run callback on the exampleApp module

AngularJS does something clever, which is to ensure that modules on which there are dependencies have their callbacks invoked first. You can see this in the way that the callbacks for the exampleApp.Services module are made before those for the main exampleApp module. This allows modules to configure themselves before they are used to resolve module dependencies. If you run the example, you will see JavaScript console output like the following:

  • Services module config: (no time)
  • Main module config: 16:57:28
  • Services module run: 16:57:28
  • Main module run: 16:57:28

We able to use the startTime constant in three of the four callbacks, but we can’t use in the config callback for the exampleApp.Services module because the module dependencies have yet to be resolved. At the moment the config callback is invoked, the startTime constant is unavailable.

As this article is also a part of Concepts while working with Angular JS Application . So, you must read other tutorials in order to complete understanding to developing Angular JS Application. Since, we are going to learn several concepts. That's why I have broken this article into several small article. Which allow us to easily understand several Angular JS features and concepts. Following are the list of articles.

Problems Solutions
Create an AngularJS module. Use the angular.module method.
Set the scope of a module. Use the ng-app attribute.
Define a controller. Use the Module.controller method.
Apply a controller to a view. Use the ng-controller attribute.
Pass data from a controller to a view. Use the $scope service.
Define a directive. Use the Module.directive method.
Define a filter. Use the Module.filter method
Use a filter programmatically. Use the $filter method.
Define a service. Use the Module.service, Module.factory, or Module.provider method.
Define a service from an existing object or value. Use the Module.value method.
Add structure to the code in an application. Create multiple modules and declare dependencies from the module referenced by the ng-app attribute.
Register functions that are called when modules are loaded. Use the Module.config and Module.run methods.

Summary: You should read above mentioned articles in order to completely understanding to developing an Angular JS application. This article is a part of Concepts while working with Angular JS Application, which is divided in to pieces of tutorials in order to understand easily. I hope you will like this article and find it useful.

Keen to hear from you...!

If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help.

About the author

Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes, Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!!

blog comments powered by Disqus