Blog

AngularJS Directives

  • (4.0)
  •   |   395 Ratings

What are AngularJS Directives?

AngularJS provides us with a provision to extend the original HTML elements with newer attributes, and the amalgam of the original element with added features are coined as DIRECTIVES. On the whole, AngularJS Directives can be thought of markers on a DOM element (just like an attribute, element name or CSS) which tell the AngularJS’s compiler ($compile) that the element comes along with additional behaviors (example, by event listeners or the like). 

How to use built-in AngularJS Directives?

Now that you know what directives are (well, superficially), AngularJS provides a set of directives by default and also provides a provision to create your own new ones. The built-in AngularJS directives are the ones with the prefix ng- and there are quite a few that we would want to introduce right away. A thorough list of all the available AngularJS built-in directives can be found here.

ng-app AngularJS directive is used to initialize an AngularJS application
ng-init AngularJS directive is used to initialize application data with values
ng-model AngularJS directive is used to bind the value of HTML controls with any of the application data that we might, using the ng-init directive as explained above.

Let’s look at an example to understand, where and how these directives could be used. If you’re not able to understand everything on the first go, don’t panic – there’s clear explanation below on how each of the element works (also helps you with the technical know-how about these directives).

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="" ng-init="seriesName='Game of Thrones'">
<div ng-app="" ng-init="episodeNumber='Season 4'">
<p>Input something (if you wish):</p>
<p>TV Series: <input type="text" ng-model="seriesName"></p>
<p>Episode  : <input type="text" ng-model="episodeNumber"></p>
<p>You're referrring to wrote: {{ seriesName + ' ' + episodeNumber + ' -> Spoils of War' }}</p>
</div>
</body>
</html>

If you run the above code, you should be able to see the following displayed on your browser:

Now let’s try to understand what each of the directives used means to achieve the final output that we are seeing. To start with, the ng-app directive tells AngularJS that the

holding it owns your AngularJS application. In other words it defines the root element of your AngularJS application, and also it will automatically initializes the application when you load your page. The ng-init directive tells what each of the parameters namely ‘seriesName’ & ‘episodeNumber’ would hold by default for your AngularJS application. Using ng-init is not very suggestable and in the coming sections, you’ll understand how to initialize data using controllers. Now trying to understand the ng-model directive, it tells that the element matches the tags. ng-model can also be used for providing type validation checks for data types, provide CSS classes for HTML elements and also to bind HTML elements with the HTML forms correspondingly.

In the example above, we have also shown the concept of ‘Data Binding’ – which in AngularJS is to bind AngularJS expressions to AngularJS data from the application. {{ seriesName }} is therefore bound with ng-model=”seriesName”.

Want To Get AngularJS Training From Experts? Enroll Now For Free Demo On AngularJS Training.

How to create new AngularJS directives?

AngularJS directives can be broadly classified into four flavors, namely:
A new HTML element
An attribute on an element
As a class
As a comment

This background should be good enough for us to get onto the quest of writing our own custom AngularJS directive. A directive can be treated the same way as a controller for its registration. The difference would be that while registering a directive you get a directive definition which has a lot of properties to configure the directive. Let’s get down to some action in creating a custom directive then:
    var justAnotherVariable = angular.module(‘myAngularApplication’, []);
    app.directive(‘customDirective’, function(){
        return {
            restrict: ‘AE’,
            replace: ‘true’,
            template: ‘

Hello AngularJS Aspirants, this is my custom directive!!!


        }
});

Using app.directive() we have registered a new custom directive named myCustomDirective. The function, which is the second parameter to the command above is the directive definition that we were discussing earlier. Let us be HTML5 compliant to access our new directive in this format (shown below):

<div data-custom-directive></div>

OR

<div x-custom-directive></div>

That should be it, the directive created above does nothing much than display some static text. But there are some interesting facts that can be understood about the properties that are used in the directive definition object to configure it.

1) restrict: This property conveys how the directive can be used in an HTML as. Since that we’ve set it up as AE, this directive can be used as a new HTML element/attribute.

2) template: This property is nothing but the HTML markup that will be compiled and linked by AngularJS. Here for an example, we have limited it to a simple string but in actual this can be much more complex including other directives or expressions.

3) replace: This property specifies that the generated template will replace the HTML element upon which our custom directive is invoked. Since that we’ve set it to true, the final output would be Hello AngularJS Aspirants, this is my custom directive!!!

Checkout AngularJS Interview Questions

Tips & Tricks to debug your directives:

This section talks about simple tips and tricks that can be applied to help you debug your directives code more efficiently. The very need of it is because of the compiled version of the directives won’t be sufficient to analyze issues. If you want to see the actual directive that was used – then you want to rely on the uncompiled version of the directive. In such a case, you might want to use ng-non-bindable. To explain this a little better, let us take an example of a widget that prints the current season’s episode names of the famous TV series (Game of Thrones). 

<ul>
<li ng-repeat="episodes in season7">{{episodes}}</li>
</ul>

The episodes's scope variable will be coming from the controller, and it would give the following as the output:

Now, if you wanted to check the actual directive usage, then this code should be helpful. It will enable you to see the uncompiled version of the code, thus enabling you to debug your directive efficiently.

<ul ng-non-bindable="">
<li ng-repeat="episodes in season7">{{episodes}}</li>
</ul>

Now with the change above, the output is definitely going to be different than the earlier:

How to Unit-test your AngularJS directives?

Now that you’ve covered the major chunk of the AngularJS directives development, now is the time for you to concentrate on how you test these to prevent any possible bugs. This section will not give you deep insight into the Unit test framework as such, but will definitely be good enough to get things started. Let’s use Jasmine for unit testing and Karma for the unit test runner. Karma can simply be installed on your system by running the following command - npm install -g karma karma-cli (This works under the expectation that you have both Node.js and npm installed on your system). Once the installation is completed, get on to a command line and run karma init.

You can answer the questions that pop up, like which testing framework to use (jasmine), want to capture any browsers automatically (Chrome) and etc to finish the installation process. Executing all the tests that are configured in your karma conf is as simple as right clicking on karma.conf.js and then click on Run karma.conf.js. You can also run tests with the karma start command line in the project root folder. That is all which is required for you to setup and execute all your tests using karma.

Explore AngularJS Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!
 
Conclusion:

AngularJS is the best available UI framework to develop modular and testable web projects within no time. There are many other flavors of such UI frameworks, but none that matches the might of AngularJS. It becomes very important to gain deeper knowledge into all of the available directives to build a pleasing application and to also know what is available for ready usage and what needs to be developed based on your project requirements. The more you practice, the more you will be able to appreciate the inner workings of these directives. I hope that this article has helped you understand both the built-in and new AngularJS directives well.


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules