Skip to main content

Directives - Understanding it



Directives push HTML syntax to another level by allowing user to create custom elements and attributes. These custom elements and attributes allow user to create an abstract user components that is usable throughout the application. There are many way to take advantage of Angular Custom Directives based on client requirements. Although we may consume the built-in directives that came out of the box by Angular. There will be at some situation that we might need to customize our directives. Let's cut to the chase and jump on how to create a simple Custom Directive

The Code
From the code above we started by
1. Create the directive component
We start by creating the directive component function by passing some parameter as an arguments ( In this case it is $location, $modal, $routeParams ) It will then return our custom directive, the custom directive is consists of templateUrl, restrict, scope, link and many other properties.
Notice templateUrl is a string where we place the section of our HTML template.
restrict: 'E' here in our example stating that this directives is implemented as an Element in our HTML tree.
Notice at line 10 we assign a string to a scope. we also may place any function implementations method here that can be used within our Custom Directives

2. Register the directive component
Finally we register the directive through .directive method by supplying
1. Directive name as a string
2. The directive component function.

From here we may see how easy to implement Custom Directive. Lets put aside what is the content of the template HTML view. this custom directive then may be implemented in the HTML by adding as an Element like below.
Conclusion
Custom Directives is a great way to abstract out our functions and sections in our single page application. Don't get shocked if we ever met with an Index.html page that full of features but only consists of less than 30 lines .

Published on : 26-Jan-2018
Ref no : DG-WPUB-000003

About Author

My photo
Wan Mohd Adzha MCPD,MCSD,MCSE
I am passionate about technology and of course love Durians. Certified by Microsoft as MCP Since 2011. Blogging from Malaysia

Comments