AngularJS Directives: Types of directives.

We can create custom directives whenever the built-in directives don’t meet our needs, when we want create reusable functionality. So, in this post I’ll explain how to create simple custom directives.

Directives are created using the Module.directive method, and the arguments are the name of the new directive and a factory function that creates the directive. Directives could be used(applied) in four ways – attribute, element, class, comment . Using the restrict property we can specify which directive type we want to use:

    .directive('myDirective', function () {
    return {
        restrict: 'EA', //E = element, A = attribute, C = class, M = comment         
        scope: {
            //@ reads the attribute value, = provides two-way binding, & works with functions
            title: '@'         },
        template: '<div>{{ myVal }}</div>',
        templateUrl: 'mytemplate.html',
        controller: controllerFunction, //Embed a custom controller in the directive
        link: function ($scope, element, attrs) { } //DOM manipulation

types of restriction:

'A' - <span ng-sparkline></span>
'E' - <ng-sparkline></ng-sparkline>
'C' - <span class="ng-sparkline"></span>
'M' - <!-- directive: ng-sparkline -->

In addition, here is short description of some properties used in this directive.
restrict – Determines where a directive can be used (as an element, attribute, CSS class, or comment).
scope – Used to create a new child scope or an isolate scope.
template – Defines the content that should be output from the directive. Can include HTML, data binding expressions, and even other directives.
templateUrl – Provides the path to the template that should be used by the directive. It can optionally contain a DOM element id when templates are defined in tags.
controller – Used to define the controller that will be associated with the directive template.
link – Function used for DOM manipulation tasks.

In the upcoming post I will describe directives scopes.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this