Menu

Quick n dirty – Angular Directives

13th January 2015 - Angular, QuickAndDirty

Going to be doing a few of these Quick n Dirty tutorials over the coming weeks, showcasing bite size quick how-to’s on useful web tech and IT.

First up, some Angular click bait help for those who want to get stuck into the popular Javascript framework.

The Angular mantra is all about not touching that DOM with your controller, and the best way of following that rule (and create re-usable controls) is by separating as much as you can in Directives.

Directives are components which have their own scope and can be slotted into any page to show content, either by using your very own tag, or including them as an attribute.

Firstly, create an angular app.

<html ng-app="QADApp">
<head><title>QAD Angular directives</title></head>
<body>
<!-- (A) html goes here -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
<script>
var QADApp=angular.module("QADApp",[]);
// (B) your directive script goes here

</script>
</body></html>

Now, lets plan our Directive quickly.

It will show a message, based on a value.  Done.
🙂

We will use the Element style of directive by using the following HTML. note how we separate our name by the camel case in the directive configuration.

<my-message-is-shown value="bye"></my-message-is-shown>

..alongside an “E” setting in the directive’s restrict object parameter..

<script>
var QADApp=angular.module("QADApp",[]);
QADApp.directive("myMessageIsShown",[function(){
return{
   restrict:"E",
   scope:{
          value:"@"
   },
   template:"<div ng-if=\"value=='hello'\">Howde</div> <div ng-if=\"value=='bye'\">See ya</div>"
 }
}]);
</script>

I generally place the template text in a function, so the code’s readable, but that isn’t quick, or dirty!

The full page, just to show you don’t need a controller either.

<html ng-app="QADApp">
<head><title>QAD Angular directives</title></head>
<body>
<!-- stuff goes here -->
<my-message-is-shown value="bye"></my-message-is-shown>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
<script>
var QADApp=angular.module("QADApp",[]);

QADApp.directive("myMessageIsShown",[function(){
 return{
   restrict:"E",
   scope:{
     value:"@"
   },
 template:"<div ng-if=\"value=='hello'\">Howde</div> <div ng-if=\"value=='bye'\">See ya</div>"
 }
 
}]);

</script>
</body></html>

The value attribute can be called anything as it is in its own scope, so I could have done the following;

scope:{ value:"@greeting"}

and changed the attribute name to greeting and it still would work.

Have a look at the Angular directives guide for more information.

Angular Directives

You can create a directive in a separate module and then inject it into the original module like below. I won’t show the whole script, you should be able to work it out. 🙂

var QADApp=angular.module("QADApp",["QADDirectives"]);

See you next time!