Thursday, 15 May 2014

Basic AngularJS Directive

Below is a basic example of using AngularJS directive:
<!--HTML markup-->
<div my-directive></div>

//JavaScript codes
var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function () {
    return {
        restrict: 'A',      // possible values: A, C, E, M
        template: "{{controllerData}} <mark>This is my custom directive. '{{directiveData}}'</mark>",
        link: function (scope, element, attrs) {
            //execute a function then assign a value
            scope.directiveData = "Good morning!";
            // can change any scope value in the outside as well
            // scope.controllerData = "test";

            element.on('mouseover', function () {
                element.css('font-size', '18px');
        },
        replace: false  // remove the outer container
    };
});
restrict property is used to determine which part of origin HTML markup to be matched. The possible values are:
- A - attribute
- C - class, i.e. <div class="my-directive"/>
- E - element, i.e. <my-directive/>
- M - comment, i.e. <!--directive:my-directive-->
The values can also be combined.

template property is used to specify the markup to be added as part of the directive. The markup will be added to the existing container or replace it depending on the replace property value.
Note from the example that we can pass data that is specific to the directive or data from the controller.
If the additional markup is much then we should use templateUrl property instead.

link is used to manipulate scope variables and the directive markup (after combined with the additional markup inside template or templateUrl property if used). It accepts three required and one optional parameters:
- scope - this is the AngularJS scope object
- element - the origin element that is matched, if it is replaced then this is the new element from the template
According to AngularJS documentation, the element is actually a jqLite (a light version of jQuery library from AngularJS) wrapped element. The library contains core functionalities of jQuery and has almost identical API.
However, important to note that if jQuery library is loaded prior to AngularJS libraries then the element will be jQuery wrapped instead so it will have full jQuery functionalities.
- attrs - attributes of the origin element that is matched, if it is replaced then the attributes of the new element from the template
- controller [optional] - to pass the directive's controller instance to be accessible inside the function

On the next post, we will see more advanced examples of AngularJS directive.


References:
AngularJS Developer Guide - Directives
GitHub - AngularJS - Understanding Directives