Simple AngularJS directive

angularjs

So I found many articles on using AngularJS directives, which go into great detail for very complex directives. I couldn’t find any on just a relatively simple directive, so I thought I’d write about it.

First of all, an AngularJS directive defines a reusable HTML tag that you can use in your HTML files. It’s very useful if you want to create some complicated custom tags, or even just simple ones, that you can reuse everywhere.

In my case, I just wanted to give my users a message for them to add the system email to their spam filter allow list, so no system-generated emails get blocked. I wanted to do this everywhere an operation included a system-generated email to the user. I wanted to style the message in a particular way, translate it according to the user’s preferences, and I didn’t want to copy/paste it in those several places. I thought it would be difficult in case I wanted to change the styling, wording, or so on, I’d have to do it in many places. This is where an AngularJS directive becomes useful. I can define the directive in one place, and use it in many places.

This is how the directive is defined in JavaScript:

.directive('emailSpamMessage', function() {
  return {
    template: '

<span class="label label-danger">{{"NOTE" | translate | uppercase}}</span> {{"SPAM_MESSAGE" | translate {HOSTING_NAME:CONSTANTS.HOSTING_NAME,SYSTEM_EMAIL:CONSTANTS.SYSTEM_EMAIL} }}' 
  } 
})

And this is how it would look in HTML:

<email-spam-message></email-spam-message>

And that’s it! Note that the directive in JavaScript is defined as emailSpamMessage, but in HTML as “email-spam-message”. AngularJS does the conversion for you.

Also note that in the controller associated to the HTML that the custom directive is in, needs to have the correct includes for it to work fully. For my particular example the controller will need to have $translate (angular-translate) and a CONSTANTS variable included.

Leave a Reply