Thursday, October 10, 2013

Using common directive across multiple modules in Angular Js

Angular Js has many inbuilt directives which we very often use in our html pages. Even though we are facilitated will a wide kind of directives some times we come across situations where we should design our own directives.While creating our own directive keep in mind that it should be reusable across all modules of your project.

Sharing directive among modules:

That's cool,now many fresh devolopers may find it hard to know how to make the custom directive file shared across multiple modules they build in their project.
Let us make it declarative using a simple example ,so that you would get a better figure.

First we shall create a couple of modules belonging to your project.
var myApp = angular.module('module-one',[])

var myApp = angular.module('module-two',[])

Now let us append a directive to one of the modules

var myFirstApp = angular.module('module-one',[]).


// implement your custom behaviour


Now you need the same directive to be used in your module-two.What will you do?will you create a new directive for it.
No !you should'nt ,you have to make the directive defined in module-one reusable in the current module.
It can be done very easily, see the following piece of code below,,
var myApp = angular.module('module-two',[module-one])
That's all ,i just added module -one to the dependancies array of module-two.Now module-one's total belongings could be exposed in module-two.It can use the directive of module-one,thus avoided duplication achieved reusability.
In this way you can just add as dependancies to any number of modules and use the common functionality across multiple modules.

Sharing common directive between applications:

In the same way if two different files are present for directives in two different applications ,but belonging to the same project,you can use the same intellegence what we have done across multiple modules. Let the two different directive files be

// application 1
var myApp1=angular.module('myModue',[])




//custom behaviour


//application 2

var myApp2=angular.module('myModule',[directive.two])




//custom behaviour


Note: While dealing with different applications don't forget to render the script files of the application in to your native application.

Like this we can make simple use of the dependancy array in our angular js application module and minimize redundancy and make our application less complicated.

No comments:

Post a Comment