< Back to AngularJS, Coding

Custom Directives in Angular

What custom directives let you do is package a whole lot of functionality and display it in just 1 line. Here is an example of making a custom directive in the js:

app.directive("projectDescription",function(){
        return{
            restrict:'E',
            templateUrl:'projectDescription.html',
            controller:function(){
                this.projects = projectsVar;
            },
            controllerAs: 'customCtrl'
        };
    });

We give it a name, ‘E’ means it’s an element (you’d use ‘A’ if it was attribute directive ie attached to element as an attribute), and tell it the html file to pull the code from. We also put the controller functionality here if we want and give it an alias.

Then in the HTML we just use

<project-description></project-description>

to display what we want. An important thing to note is that capital letters don’t work in custom directives and using a dash or underscore needs to converted to a capital letter following it, in this example ‘projectDescription’.

View the demo

Download the demo

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *