AngularJS : Getting started with Directives

25 / Apr / 2013 by Suroor Wijdan 0 comments

In this post we will go through an important aspect of AngularJS i.e., Directives.

Directives helps us do things in a better and cleaner way. Lets get into the code rather going into theoretical explanations, which will make it more clear what actually directives do.

We have written a simple directive below which shows some HTML when the element being created is encountered.

[html]

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js" type="text/javascript"></script>

</pre>
<div></div>
<pre>
<script>// <![CDATA[

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

myApp.directive(‘mytag’,function(){
return {
restrict: "E",
template: "<strong>This is a great First Directive</strong>",
replace: true,
}
})

// ]]></script>

[/html]

In the above code, we have “mytag” element which when encountered in HTML renders the corresponding template.  Lets see what the code does,

myApp.directive() is another syntax that we have to remember. The first argument in this is the name of the tag that you want, in our case its “mytag”. Second thing is a factory function which returns an object that defines the directive properties.

In this object we have set “restrict” as E which makes it an Element that can be used like any of HTML tags. The second option “template” defines the HTML template to be loaded and the third option “replace” if set to true replaces the current element with the template.

We will learn more about other options available to us in the next post.

Hope it Helps! Feel free to ask if you have any queries.

Read Further on AngularJS Series

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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