Rajeev Kannav Sharma

Posts About

AngularJs Directives Restrict to Elements and Attributes

09 Jun 2015

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

Best Practice:

Prefer using directives via tag name and attributes over comment and class names. Doing so generally makes it easier to determine what directives a given element matches.

<!-- avoid -->
<div class="my-range-slider"></div> 

/* avoid */
angular
    .module('app.tools')
    .directive('myRangeSlider', myRangeSlider);

function myRangeSlider() {
    var directive = {
        link: link,
        templateUrl: '/template_path/filenamehtml',
        restrict: 'C'
    };
    return directive;

    function link(scope, element, attrs) {
      /* */
    }
} 

<!-- recommended -->
<my-range-slider></my-range-slider>
<div my-range-slider></div>

 

 /* recommended */
angular
    .module('app.tools')
    .directive('myRangeSlider', myRangeSlider);

function myRangeSlider() {
    var directive = {
        link: link,
        templateUrl: '/template_path/filename.html',
        restrict: 'EA'
    };
    return directive;

    function link(scope, element, attrs) {
      /* */
    }
}

Note: EA is the default for AngularJS 1.3 +

And if you get stuck… Ask Here

email me rajeevsharma86@gmail.com

Tweet to me at @rajeevkannav.