Jan 19, 2016
Creating a custom directive
Angular JS provides us with multiple directives straight out of the box, this is awesome but in some cases we have requirements that are not met by the out of the box directives. The solution to this problem is that we can create our own Custom Directives within our Angular JS Application.
When you are interested in creating your own directive you need to know how to register the directive to your Angular JS module, you can do this by using the “module.directive” API. The “module.directive” needs a name followed by a Factory function.
In the previous code sample I have only structured the outlines of a directive and we need to add some logic within the directive to make it useful. When you are creating your directives you have to make a decision on what data needs to be displayed and how to display it, this data is normally information you want to work with multiple times.
In my example I will be retrieving the firstname, lastname, job title and nationality of myself. When creating your directive you have to specify a “return” clause to tell your angular app what data it should return, in this return clause you have a lot of properties you can specify such as “template” that will inline HTML markup or you could even use “TemplateURL” that will accept a path to a HTML document with the markup. The latter option is used more common with complex templates.
Next, I will be creating a very basic controller so that we have some information to work with.
In this controller I have created a scope object called “trainer” (line 16) and it will contain the 4 properties and corresponding values to be used by the directive. Finally we just need to add the directive onto our HTML where we want the information to be displayed. Remember that this directive is created within the “CustomDirApp” module and will only be available inside that module.
Our last step includes creating the HTML page that will contain the directives for our angular module, controller and most importantly our Custom Directive. To do this we first need to add a reference to our Angular Script file (seen on line 6), then we can add div elements that contains the directives we are interested in. On line 9 we have the ng-app and ng-controller to specify where the Angular application and controller starts, and on line 11 we create an element that will reference our Directive by name that we specified in the second screenshot.
Within this screenshot I create an element with the name of the directive, we could have easily used a div element with an attribute that points to the same directive. Now whenever I need to display my own information I simply call the directive and I will have the information.