Custom Directives in Angular

Posted on

in

,

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

Leave a Reply

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

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930