15

Angular provides us with a mechanism to write directives - which is extremely powerful in what it can do. But the thing I keep wondering is - in what scenario should you be actually writing a custom directive of your own.

We keep seeing questions in and around Stack Overflow with various people attempting to write directives which ( in my opinion ) need not be written in the first place. In most cases they can be solved with a combination of repeat, switch and show. See examples of questions containing directives that I think shouldnt be directives in the first place!

https://stackoverflow.com/questions/16101073/angularjs-directive-is-not-working-in-ie-10

Fire button click in AngularJS

angularjs: using a directive inside the ui-bootstrap modal

Some examples scenarios. I am not picking on them in anyway..because I am sure it is not clear to anyone when we should be using / writing a directive.

We see scenario's where people use directives as a mechanism for templating. Is this the right way of doing things? Or is there a better way? ( ng-include perhaps? ) Are there any upsides / downsides to using directives as a templating mechanism? The reason for this question is that sometimes I wonder if people write directives because coming from the jquery world the first thing they can think of is writing DOM manipulating code and since the Angular way is to not manipulate the DOM in controllers it all gravitates towards writing all that code in a directive.

EDIT :

I believe this confusion ( of shoving things inside a directive ) arises because Angular does not have a separate concept of a "view" - unlike Backbone ( which only has a "view" but no component! ). Directives are amazing at defining components - But I think if you use them to create "views", you will lose some of the "angular" way. This is my opinion though -which is why I am soliciting what the rest of the angular community thinks.

The good thing about simpler directives ( directives that do just 1 thing! ) is that they are absolutely easy to test. If you look at all the ng directives they all do 1 thing and do that thing pretty well.

What is the best way of defining reusable "views" ( not components! ) in Angular ? Should that be written in a directive? Or is there a better way?

It would be awesome if one of the Angular Dev's have an opinion in this matter!

Community
  • 1
  • 1
ganaraj
  • 26,841
  • 6
  • 63
  • 59
  • 1
    as soon as you want to do DOM manipulation you need to write a directive. Controllers should not have a single do manipulation in them. But directive can have controllers inside them. – mpm Apr 09 '13 at 10:08
  • directive controllers are for some other reasons. Those controllers and the normal controllers are different. – ganaraj Apr 09 '13 at 14:57

2 Answers2

11

Well... quite a good question.

I believe directives are mainly meant to "extending HTML so you can build a DSL", improving productivity and code quality.

The question is that this is achieved through componentizing things. But it is of most importance that we understand that directive is not about visual components only, neither templating only, but also, about behavior.

To summarize, using directives you could:

  1. create a DSL to augment elements behavior
  2. create DSL widgets, so you can stop repeating yourself
  3. wrapping already existent components, buying you productivity.
  4. optimization

Augmenting behavior is nothing more than componentizing behavior. ng-click, for example, adds the clickable behavior to any element. Imagine you're creating an app with dozens of draggable elements. Than you would create a directive to augment element behavior, making it draggable without even touching the element visual (<span draggable>Test</span>). Yet another example, imagine you gonna have special hints on mouse hover. title attribute is not suitable to this, then you can create your own my-title attribute, that automatically create your "special hint" on mouse hover (<span my-title="Some caption">Test</span>).

And when developing an app, you have a plenty of domain specific concepts and behaviors. Stackoverflow, for example, have a strong concept of voting. You can vote up/down questions, answers, comments... So you could create a reusable votable directive, that would add "vote behavior" and "vote widget" (up/down arrows) to praticaly any element.

This last one gives us another face: templating. Not only for lazy ones, but to improve code quality and maintainability following DRY principle. If you are repeating controllers code, HTML structure, or anything else, why not templating and componentizing it, right? Directive is your guy for this job.

Of course, you also have some generic application of directives. Many application (not to say all of them) rely on clickable elements, this is why we have a ng-click, for example. Many applications have upload areas. And what would you do in a jQuery way of thinking? You would create a jQuery plugin. Right? In Angular, you would create a Angular Widget (using directives). You could even wrap an already existing plugin using a directive, and, once more, augmenting its behavior so it can smoothly talk to your application.

Regarding wrapping plugins, to every jQuery plugin (but could be MooTools, Ext...), you gonna have to create a controller, call $('element').plugin() on it, and caring that jQuery events change and $digest your scope for you. This is another perfect use of directive. You can create a directive that apply .plugin() on your element, listening to the events and changing/digesting your scope for you. This is what Angular UI Project is all about, take a look.

One last point is the optimization. I recently created and app that creates tables with dynamic columns and rows (a grid). The question is that data is updated in real time! And the ng-repeat inside ng-repeat, to create headers, was killing application performance (nested loops in every $apply cycle, happening each half second). So you can create a directive that create the columns template and still use ng-repeat inside it, but you would have a loop through columns only upon columns edition.

So, wrapping up, I believe directives are about componentizing behavior and form (templating), which buy you producitivity and code quality.

Caio Cunha
  • 23,326
  • 6
  • 78
  • 74
2

I personally write directives quite a lot, as they tend to make my program much more declarative.

An example: in a JSON -> HTML form parser I made recently, I created a "form-element" directive, that parses the JSON element a creating the necessary directives as it's children. That way I have a directive for each field type, with specific behavior and methods. Also, any common behavior shared between all elements is in the form-element directive.

This way, a group element is a directive with a ng-repeat in it's template, and a title element is as simple as a h1. But all can have the same conditional behavior (a group can only appear if a previous field has a certain value set, for instance). And all extremely clean - any time i need to add/change, it all stays perfectly put, and the html is extremely declarative.

EDIT - included a snippet of code, as requested via comments.

  /**
  * Form Element
  * ============
  *
  * Handles different elements:
  *   Assigns diferent directives according to the element type
  *   Instanstiates and maintains the active property on the formElem
  */
  .directive("formElement", ['$compile', function($compile){
    return{
        restrict: "E",
        scope:{formElemModel: '='},
        link: function(scope, element, attrs){
            var template = '';
            var type = scope.formElem.type;
            switch (type){
                case "field":
                    template = 
                        "<form-field-"+scope.formElemModel.fieldType+" ng-switch-when='true'>\
                        </form-field-"+scope.formElemModel.fieldType+">";
                    break;
                default:
                    template = "<form-"+type+" ng-switch-when='true' ></form-"+type+">";
                    break;
            }
            element.html(template);
            $compile(element.contents())(scope);

        // Active state of form Element
        scope.formElem.active = true;
        scope.testActive = function(){
          if(scope.$parent.formElem && scope.$parent.formElem.active == false){
            scope.formElem.active = false;
          }
          else{
            scope.formElem.active = 
              scope.meetsRequirements(scope.formElem.requirements);
          }
        }
        scope.$watch("meetsRequirements(formElem.requirements)", scope.testActive);
        scope.$watch("$parent.formElem.active", scope.testActive);
        }
    }
  }])
Tiago Roldão
  • 10,629
  • 3
  • 29
  • 28
  • so you are basically using it for templating. That is one use case. If you are alright creating element level directives ( which means that you dont care about html validation! ) this is perfectly fine. Have you considered using ng-include instead of a directive for this scenario? Ofcourse a custom named directive is much more semantic. But just wondering. Perhaps the question is - is it even possible to do the same with ng-include! – ganaraj Apr 09 '13 at 10:37
  • In a few cases (such as a simple h1) it may be just templating, but it certainly isn't on more complicated elements, such as a ajax loading multiple select with select2, and callbacks defined in the JSON :) It really isn't possible to do most of what is done (in my case) in a ng-include, but even in the cases where it is, why do so? trying to do extremely complex structures using only html seems overusing the template system, and of course (and in the case of the h1) I'd replace my one line of inline template with an extra call to an html file, all with extra headers. – Tiago Roldão Apr 09 '13 at 10:44
  • (double post, sorry) in my case, ng-include would mean a) 15+ html files just for fields or b) loads of ng-switch directives (which useful as they are, tend to get rather messy) and if I wanted specific model behavior, either throwing functions to a messy dump controller, or having 10+ controllers, that could (and should) just be directives. *(Also, as i should note, having it all-js makes it dead easy to use as the widget that it is)* Regarding html validation, you can do all this with classes, or data-prefixed attributes - although I must admit, it is true, I don't care :P – Tiago Roldão Apr 09 '13 at 10:52
  • Can you please share a code example of the directive you mentioned above (form-element) – dazzle Apr 09 '13 at 11:11
  • @ganaraj `dont care about html validation` ...no reason directives can't all be valid html. Can use `data-` attributes or class to identify directive element(s) – charlietfl Apr 09 '13 at 14:04
  • @charlietfl I mentioned element level directives. I know we can have valid attribute or class directives. Element Directives are also more semantic and I would use them if I was asked not to care about html validation. – ganaraj Apr 09 '13 at 15:11
  • @TiagoRoldão Yeah. Its an element directive. Between I am not sure how testable this is. See my edit to the question. I thought a clarification was in order. Perhaps a revised question is - should we be using directives for views ? ( as opposed to components! ). – ganaraj Apr 09 '13 at 15:28
  • @ganaraj I use them because I can, basically - this specifically is a tool for internal use, and I can skip pesky little things like validation ;) But it really doesn't change anything about the original question, does it? Also, with the right markup care, both functional classes and data-prefixed attributes can be pretty declarative and straightforward. – Tiago Roldão Apr 09 '13 at 15:31
  • @ganaraj (regarding revised question) I love the declarative nature of angular exactly because of this (and that is why I hate sharing snippets of code out of context) - these are *components* in their true sense - even if some behave just as templates (at least in the "frontend", as they're to be mirrored with components on the builder side of the app) they hold in them the whole logic that is specific for each component. Again, If I treated them as "views", I would either have to create separated controllers, increasing code size, or throw all logic to a big bag called `insanityCtrl()` ;) – Tiago Roldão Apr 09 '13 at 15:37
  • I realize now I may seem overzealous over the way I view directives - that couldn't be farther from the truth! I'm just making there is no confusion over why I choose to use them, not claiming it to be the true and only way! – Tiago Roldão Apr 09 '13 at 15:45