1

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.

0

1 Answer 1

3

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);
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

How about if I change rootscope property to make it reflect to what I append to the document. I mean I need not just interpolated HTML, but a working app, that is bound to scope and has events/etc?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.