What is a directive in AngularJS?

AngularJS Directives Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

A directive is a reusable marker on an element or attribute that tells AngularJS to attach behaviour or transform the DOM. Built-ins include ng-model, ng-repeat, ng-if, ng-click. You write custom directives for reusable components and DOM manipulation, defining a template, a scope (often isolated), and a link function that wires events and watches.

A directive is how AngularJS extends HTML. ng-repeat, ng-if, ng-click are all directives, and I write my own for reusable UI pieces or when I need to touch the DOM directly. In the definition I set restrict for how it's used — element or attribute — a scope, usually an isolate scope with @, = or & bindings so it doesn't leak into the parent, a template, and a link function that runs for each instance to bind events and set up watches. In AngularJS 1.5+ the component() helper is the cleaner way to build these, and it's also what maps most directly onto components if you're migrating to a newer framework.

A directive definition object controls:

  • restrict — where it can be used: E element, A attribute, C class, M comment.
  • scope — false (share parent scope), true (child), or an object {} for an isolate scope with bindings: @ (string), = (two-way), & (expression/callback).
  • template/templateUrl and transclude for wrapping content.
  • link(scope, element, attrs) — runs per instance; bind DOM events, set $watches, manipulate the element.
  • controller — for logic and for exposing an API to other directives via require.

Custom directives were AngularJS's component model before component() was added in 1.5, which is the recommended style for migration toward Angular/other frameworks.