Blogger news

Blogger templates

Wednesday, July 30, 2014

Module Loading in AngularJS


Today after reading my  introduction blog on AngularJS one of my friends asked me doubt, "How Angular modules will know about it's controllers. His question was really very valid because module and controller I created was two different files and in two different directories. Then how module is aware about controller?
Well Angular is brilliant enough to know all dependency of the associated main module. Before explain how module knows it's dependencies I will show a diagram which depicts how module is related to other components. 



As you can see in the image module is the route of all other utilities, it means module is a container.

Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is evaluated if at that time document.readyState is set to'complete'. At this point Angular looks for the ng-app directive which designates your application root. (Most of the the time ng-app will be in the route of html. eg:- <html ng-app="MainModule"/>) .If you are familiar with C# or Java "Main" method is the entry point to application but in AngularJS entry point will be the module you mentioned in ng-app directive. Once ng-app directive found Angular will load module associated with the directive. Once main module is loaded  it will  inject all other components like filtersfactory, service, routes, controller or other components in the above image. 


Modules are the an important part  for Angularjs’ dependency injection system. The beauty of Angularjs is that it is declarative, and by making declarations in your modules, you are telling Angularjs about all the objects you are going to need for your application to run and how you want it to load them right at application startup. That way, any time you need a particular object, it is already available and all you have to do is ask for it. Modules provide a way to group dependencies for a functional area of your application and a mechanism for automatically resolving those dependencies.

Below picture depicts module load cycle in Angular,






If you are not familiar what requirement is then I will show  the syntax of declaring module is Angular. I hope you all ready go through 

Syntax:-
var ModuleName = angular.module('ModuleName',[requires]);.

 Assume my main module has dependency to other two module, module1 and module2 then module declartion will be,
Var MainModule = angular.module('MainModule',['module1','module2']);

Here module1 and module2 are requires.

No comments:

Post a Comment