2

I have an AngularJS app which (reduced to relevant parts) looks like this:

<div ng-app="myModule">
    <div id='container'>
        <div say-hello-to name="Frank">f</div>
        <div say-hello-to name="Billy">b</div>
    </div>
</div>

the application works fine. Now, if after the angular bootstrapping process, I add a new dom element, which corresponds to a directive, it isn't interpreted. Note that the "Addition" is done by non-angularjs JavaScript Code.

<div say-hello-to name="Dusty">d</div>

it is just "dead" div.

JsFiddle Link: http://jsfiddle.net/Nn34X/

The question is: How can I add a new DOM Element into the application and let AngularJS know that there is a new Element to be interpreted (I could easily point angularjs exactly to all inserted elements)

Cheers, and thanks in Advance!

5
  • 1
    Do you have to add those elements in a non-angular js code? Commented Apr 16, 2014 at 9:49
  • if you are adding the element with jQuery you need to compile it first Commented Apr 16, 2014 at 10:17
  • @OmriAharon: yes, it needs to be non-angular code Commented Apr 16, 2014 at 10:40
  • @doodeec: compile how? do you have an example? Commented Apr 16, 2014 at 10:41
  • @iPirat have a look at groups.google.com/forum/#!topic/angular/Ul3XTt6NCfY Commented Apr 16, 2014 at 10:43

1 Answer 1

5

Retrieve the $injector service:

var $injector = angular.element(document.querySelector('#container')).injector();

Select the element:

var element = angular.element(document.querySelector('[name="Dusty"]'));

Use the $injector service to retrieve the $compile service and link the element to the scope:

$injector.invoke(function ($compile) {    
  var scope = element.scope();
  $compile(element)(scope);
});

Demo: http://jsfiddle.net/6n7xk/

Short explanation: Call Angular JS from legacy code

Sign up to request clarification or add additional context in comments.

1 Comment

As a follow-up: if REMOVING such an element using non-angular code, is it enough to do angular.element(...).scope().$destroy() or is there anything else to consider?

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.