IttayD
IttayD

Reputation: 29123

Why do I need $compile when `compile:` seems to work fine

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?

Upvotes: 0

Views: 55

Answers (1)

New Dev
New Dev

Reputation: 49590

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.

Upvotes: 1

Related Questions