AngularJS : Getting started with Directives
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
- AngularJS : A “Write Less Do More” JavaScript Framework
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Adding Items to a JavaScript List and updating corresponding DOM Dynamically
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS