Evgenyt
Evgenyt

Reputation: 10721

AngularJS - Is it possible to compile and link template from code?

How do I make the following code append 2 to the document?

var $injector = angular.injector(['ng']);

$injector.invoke(function ($compile, $rootScope) {
    var link = $compile('<p>{{1+1}}</p>');
    var newElement = link($rootScope);

    $(document.body).append(newElement);
});

What I now see in browser is

{{1+1}}

EDIT

I want the added to body element, not just be interpolated static HTML, but to be an angular app - so that it reflects changes in scope, has event handlers, etc.

Upvotes: 1

Views: 313

Answers (1)

zs2020
zs2020

Reputation: 54514

You need that to be bound to the $scope rather than $rootScope, change the line to

function ctrl($scope) {
    var $injector = angular.injector(['ng']);

    $injector.invoke(function ($compile) {
        var link = $compile('<p>{{1+1}}</p>');
        var newElement = link($scope);
        $(document.body).append(newElement);
    });
}

Or, you can use $interpolate module.

function ctrl($scope, $interpolate) {
    var $injector = angular.injector(['ng']);
    $injector.invoke(function ($compile) {
        var link = '<p>{{1+1}}</p>';
        var exp = $interpolate(link)({});
        $(document.body).append(exp);
    });
}

Upvotes: 3

Related Questions