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.

<script src="" type="text/javascript"></script>

<script>// <![CDATA[

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

    return {
        restrict: "E",
        template: "<strong>This is a great First Directive</strong>",
        replace: true,

// ]]></script>

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


Leave a comment -