Search code examples
javascriptangularjsdomangularjs-bootstrap

AngularJS doesnt "bootstrap" new DOM elements


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!


Solution

  • 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