185

I have spent quite a lot of time reading through AngularJS documentation and several tutorials, and I have been quite surprised at how unapproachable the documentation is.

I have a simple, answerable question that may also be useful to others looking to pick up AngularJS:

What is an AngularJS directive?

There should be a simple, precise definition of a directive somewhere, but the AngularJS website offers these surprisingly useless definitions:

On the home page:

Directives are a unique and powerful feature available in AngularJS. Directives let you invent new HTML syntax, specific to your application.

In the developer documentation:

Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

And there is a series of talks about directives which, ironically, seem to assume the audience already understands what they are.

Would anyone be able to offer, for clear reference, a precise definition of what a directive is that explains:

  1. What it is (see the clear definition of jQuery as an example)
  2. What practical problems and situations it is intended to address
  3. What design pattern it embodies, or alternatively, how it fits into the purported MVC/MVW mission of AngularJS.
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
tohster
  • 6,973
  • 5
  • 38
  • 55
  • 2
    You had me at... *see the clear definition of jQuery as an example.* –  Jul 28 '16 at 10:15
  • Not sure how it was in 2012 on Stack Overflow, but I just revised this question and added the “angular-directive” tag. Its [tag info](https://stackoverflow.com/tags/angular-directive/info) actually gives quite a clear definition. Also, I noticed that I can’t find the second quote in the developer docs… – Sebastian Simon Oct 22 '17 at 16:53

5 Answers5

144

What it is (see the clear definition of jQuery as an example)?

A directive is essentially a function that executes when the Angular compiler finds it in the DOM. The function(s) can do almost anything, which is why I think it is rather difficult to define what a directive is. Each directive has a name (like ng-repeat, tabs, make-up-your-own) and each directive determines where it can be used: element, attribute, class, in a comment.

A directive normally only has a (post)link function. A complicated directive could have a compile function, a pre-link function, and a post-link function.

What practical problems and situations is it intended to address?

The most powerful thing directives can do is extend HTML. Your extensions are a Domain Specific Language (DSL) for building your application. E.g., if your application runs an online shopping site, you can extend HTML to have "shopping-cart", "coupon", "specials", etc. directives -- whatever words or objects or concepts are more natural to use within the "online shopping" domain, rather than "div"s and "span"s (as @WTK already mentioned).

Directives can also componentize HTML -- group a bunch of HTML into some reusable component. If you find yourself using ng-include to pull in lots of HTML, it is probably time to refactor into directives.

What design pattern does it embody, or alternatively, how does it fit into the purported MVC/MVW mission of angularjs

Directives are where you manipulate the DOM and catch DOM events. This is why the directive's compile and link functions both receive the "element" as an argument. You can

  • define a bunch of HTML (i.e., a template) to replace the directive
  • bind events to this element (or its children)
  • add/remove a class
  • change the text() value
  • watch for changes to attributes defined in the same element (actually it is the attributes' values that are watched -- these are scope properties, hence the directive watches the "model" for changes)
  • etc.


In HTML we have things like <a href="...">, <img src="...">, <br>, <table><tr><th>. How would you describe what a, href, img, src, br, table, tr, and th are? That's what a directive is.
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 2
    Mark, thanks. I think this is clear and probably the closest to an accurate answer. I think directives are always bound to html tags right? So perhaps it's more accurate to say that a directive is a function that is bound to an HTML tag. As such, it allows the HTML language to be extended declaratively. – tohster Dec 19 '12 at 20:22
  • Well, a directive can be used in a comment, so not all directives have to be bound to an HTML tag. E.g., `` – Mark Rajcok Dec 20 '12 at 02:00
  • Mark, would that be unconventional use of a directive? i.e. directives are conventionally used and purposed for extending HTML. – tohster Dec 20 '12 at 03:54
  • I think so. I've never seen anyone actually use a directive in a comment, although people have asked that ng-repeat be enhanced to be able to work in a comment (so that they are not forced to have an element repeated for each iteration). – Mark Rajcok Dec 20 '12 at 03:57
  • 9
    OK I have a better understanding now. One way to think about it is: **1.** DSL's usually represent [syntax trees](http://en.wikipedia.org/wiki/Abstract_syntax_tree) **2.** The HTML DOM is a DSL syntax tree but it's a rigid one: the tags are mostly rigidly designed and purposed, and not extensible. **3.** AngularJS and the directive mechanism specifically, make the HTML DOM more flexible by allowing developers to build custom tree nodes. These nodes can represent new behaviors, or aggregations of existing behaviors (sub-trees) **4.** Thus, directives allow HTML DOM to evolve into a custom DSL – tohster Dec 21 '12 at 20:25
  • 1
    @MarkRajcok I'm struggling with your last paragraph. Is plain `
    ` is a directive ? You said yes. But there is **no decoration** here ( via element,class,comment,attribute) .People here are saying that these are _re markers for a HTML DOM_ . Can you clarify ? ( I'm not talking about the cause where you can create a directive for a plain element like `
    `)
    – Royi Namir Oct 25 '15 at 14:52
  • So: `directives` are `bindings` with the option to use custom HTML tags. Terrible nomenclature. – AJB Sep 07 '16 at 08:19
11

Maybe a really simple and initial definition for angular directives would be

AngularJS directives (ng-directives) are HTML attributes with an ng prefix (ng-model, ng-app, ng-repeat, ng-bind) used by Angular to extends HTML. (from: W3schools angular tutorial)

Some examples of this would be

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-bind directive binds application data to the HTML view.

<div ng-app="">
    <p>Name: <input type="text" ng-model="name"></p>
    <p ng-bind="name"></p>
</div>

Check this tutorial , at least for me it was one of the best introductions to Angular. A more complete approach would be everything that @mark-rajcok said before.

jplozgom
  • 129
  • 3
  • 9
4

Looking at the documentation, directives are structures you can write that angularjs parses in order to create objects and behaviors.In other words it's a template in which you use mix of any arbitrary nodes and pseudo-javascript and placeholders for data to express intentions of how your widget (component) is structured, how it behaves and how it is feed with data. Angularjs then runs against those directives to translate them into working html/javascript code.

Directives are there to so you can build more complex components (widgets) using proper semantics. Just take a look at the angularjs example of directives - they're defining the tab pane (which isn't of course valid in regular HTML). It's more intuitive than using like div-s or spans to create structure which is then styled to look like a tab pane.

WTK
  • 16,583
  • 6
  • 35
  • 45
  • I added what I feel is slightly less technical explanation. – raam86 Dec 14 '12 at 09:14
  • 1
    Thanks this is quite helpful. So maybe I can think of it as a kind of dynamic template (similar to a class in O-O programming) that encapsulates a component, describes it by properties and behaviors, is capable of being instantiated, and can express itself to the DOM? And the reason it exists (vs. javascript object or html template) is to allow HTML tags to take on more dynamic, object-like behaviors so they can start to become manipulable in O-O type programming? – tohster Dec 14 '12 at 09:29
  • Yes and no. I wouldn't say that the reason *directives* exists has much to do with them being manipulable in OO programming. In fact whole angularjs approach to framework feels heavily related to HTML and arbitrary DOM nodes attributes rather than writing OO Javascript code. I get that vibe from looking at all examples of how angularjs is solving every day problems. I would say that the **main reason behind directives** is to have way to embed behaviors and data in one semantically structured component. – WTK Dec 14 '12 at 10:08
3

In AngularJS Directives are html re markers for a HTML DOM element like an attribute(restrict- A), element name(restrict- E), comment(restrict- M) or CSS class(restrict - C) that tell AngularJS's HTML compiler ($compile) to perform a specified behavior to that DOM element or even transform the DOM element and its children.Some Example are ng-bind ,ng-hide/show etc.

Vivek Panday
  • 1,426
  • 2
  • 16
  • 34
2

The homepage is very clear about this: When you hover over tabs in the last section:

We've extended HTML's vocabulary with a custom tabs element. The tabs abstracts the complex HTML structure and behavior necessary for rendering of tabs. The result is a more readable view and very easily reusable syntax."

Then in the next tab:

angular.module('components', []).
  directive('tabs', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {},
      controller: function($scope, $element) {
        var panes = $scope.panes = [];

        $scope.select = function(pane) {
          angular.forEach(panes, function(pane) {
            pane.selected = false;
          });
          pane.selected = true;
        }

So you can invent html elements i.e tabs and let angular handle the rendering of those elements.

raam86
  • 6,785
  • 2
  • 31
  • 46
  • 2
    Thanks for the quick response! So the purpose of a directive is to extend HTML's vocabulary by the creation of custom tags and attributes? That seems quite powerful, although it appears to address a much broader problem scope than "MVW". BTW others might disagree, but I would think that scrolling to the bottom of a page, and then hovering over a hyperlinked word, and then reading a pop-up tooltip that doesn't once mention the word 'directive' is not exactly a "very clear" definition of what a directive is. Nonetheless, really appreciate the speedy response. – tohster Dec 14 '12 at 09:16
  • Yes! You can check this fiddle they made. The actual html is different the the on in the html pane. – raam86 Dec 14 '12 at 09:16