Simple AngularJs Directive

Let’s take a look at a simple AngularJs directive to start getting an understanding of how directives work and how AngularJs uses them. As discussed in the previous angular post, we have to mark some outer element on the page as ng-app. A little refresher, this tells angular that it needs to run through all of the DOM elements looking for directives. Once it locates all of the directives, they are associated with those DOM elements and will run now.

So what is a directive? In the simplest form, it is essentially just a function that is tied to the DOM and gets run when the DOM gets compiled. There are multiple ways to denote a DOM element with a directive. One of the more common ways it’s done, is just like putting ng-app directive in the body tag. Lets say we have a directive called angularDatePicker; you could mark a element like follows:

 <span angularDatePicker></span>

It is as simple as that, now every time the DOM is compiled, angular will see that directive and execute it on that span each time. Now lets take a look at a data binding and model example. Two built in directives that AngularJS gives us are ng-model and ng-bind. They are more or less just different ways of invoking your own directive. In the follow snippet. You will notice that when you type in the input box, the type is bound and output on in the divs denoted by these 3 different, valid, bind methods.

<body ng-app>
    <input type="text" ng-model="myDirective" placeholder="Type Some Text.." />
    <div ng-bind="myDirective"></div>
    <div ng:bind="myDirective"></div>
    <div ng_bind="myDirective"></div>

There are two more way to do the same binding but the only difference is they are the only 2 that are HTML5 compliant and should pass HTML5 validators.

<!-- HTML5 Compliant -->
<div x-ng-bind="myDirective"></div>
<div data-ng-bind="myDirective"></div>

All 5 of the methods above are valid ways to invoking a directive.

Here is a working JSFiddle to see it in action.  Click Here

Leave a Reply

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

StackOverflow Profile