AngularJS Directives Advanced

Directives gives us template, scope bindings, bindToController, link and many other things. The usage of these should be carefully considered now that .component() exists. Directives should not declare templates and controllers anymore, or receive data through bindings. Directives should be used solely for decorating the DOM. By this, it means extending existing HTML – created with .component(). In a simple sense, if you need custom DOM events/APIs and logic, use a Directive and bind it to a template inside a component. If you need a sensible amount of DOM manipulation, there is also the $postLink lifecycle hook to consider, however this is not a place to migrate all your DOM manipulation to, use a Directive if you can for non-Angular things.

Here are some advisories for using Directives:

  • Never use templates, scope, bindToController or controllers
  • Always restrict: ‘A’ with Directives
  • Use compile and link where necessary
  • Remember to destroy and unbind event handlers inside $scope.$on(‘$destroy’, fn);

Recommended properties

Due to the fact directives support most of what .component() does (template directives were the original component), I’m recommending limiting your directive Object definitions to only these properties, to avoid using directives incorrectly:

Property Use it? Why
bindToController No Use bindings in components
compile Yes For pre-compile DOM manipulation/events
controller No Use a component
controllerAs No Use a component
link functions Yes For pre/post DOM manipulation/events
require No Use a component
restrict Yes Defines directive usage, always use ‘A’
scope No Use a component
template No Use a component
templateUrl No Use a component
transclude No Use a component

 

Share this post
[social_warfare]
Mouse and Event Directives
AngularJS Controllers

Get industry recognized certification – Contact us

keyboard_arrow_up