Thursday, November 5, 2015

AngularJS - How can we create a custom directive in Angular?

Ref:- http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers#Whatarecontrollersandneedofng-controllerandng-modelinAngular

Till now we have looked in to predefined Angular directives like “ng-controller”,”ng-model” and so on. But what if we want to create our own custom Angular directive and attach it with HTML elements as shown in the below code.

<div id=footercompany-copy-right></div>

To create a custom directive we need to use the “directive” function to register the directive with angular application. When we call the “register” method of “directive” we need to specify the function which will provide the logic for that directive.

For example in the below code we have created a copy right directive and it returns a copy right text.

Please note “app” is an angular application object which has been explained in the previous sections.
 
app.directive('companyCopyRight', function ()
{
return
{
        template: '@CopyRight questpond.com '
 };
});
 
The above custom directive can be later used in elements as shown in below code.
<div ng-controller="CustomerViewModel">
<div company-copy-right></div>
</div>

No comments:

Post a Comment