0

Check out http://jsfiddle.net/3jvoL4ew/

(Note: I know it can be done with a template:, that's not my question though)

It contains a directive that adds a button and a text to the element it is used on:

app.directive("otcDynamic", function ($compile) {
    return {
        compile: function(element) {
            var template = "<button ng-click='doSomething()'>{{label}}</button>";
            element.append(template);

        }
    }
});

It works, but the usual way such a directive is defined is:

app.directive("otcDynamic", function ($compile) {
    return {
        link: function (scope, element) {
            var template = "<button ng-click='doSomething()'>{{label}}</button>";
            var linkFn = $compile(angular.element(template));
            var content = linkFn(scope);
            element.append(content);
        }
    }
});            

So if using compile: is more concise, and more efficient when used in ngRepeat, why do people recommend using $compile?

IttayD
  • 28,271
  • 28
  • 124
  • 178
  • People recommend that? First I was aware of it. Maybe for certain scenarios where you want to prepare some details from attributes etc before introducing the template – Peter Ashwell Jan 19 '15 at 21:36
  • Not sure, good article on compile, post- and pre-link: [***article***](http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/) – Jason Goemaat Jan 19 '15 at 21:41

1 Answers1

1

I don't know about who recommends what. Each has its own use.

The directive's compile function runs once to define and return the directive's pre- and post-link functions, and is generally intended to amend the template when the directive is first compiled.

The $compile service can be employed to compile and link some content the directive receives dynamically even after the directive was created.

New Dev
  • 48,427
  • 12
  • 87
  • 129
  • Can you give an example where `$compile` is used but `compile` cannot? What can be changed in the example I gave so it wouldn't work with `compile`? – IttayD Jan 20 '15 at 06:37
  • You can look at the example in [documentation for $compile](https://docs.angularjs.org/api/ng/service/$compile#example) – New Dev Jan 20 '15 at 14:25
  • indeed, an example. it means that I can use $compile when the template is created based on user input and can completely change (there's no rule to its structure). I guess this is a very rare case. – IttayD Jan 20 '15 at 14:46
  • @IttayD, here's a [good example](http://stackoverflow.com/questions/28058702/angularjs-complex-directive-in-ng-repeat-how-to-bind-the-ngmodel-or-ngchecked/28063373#28063373) from another question that I answered. – New Dev Jan 21 '15 at 14:31