简体   繁体   中英

Apply $compile and $scope to external div text moved into ng-view element

I have a div element that I attach to one of the elements within an ng-view DOM tree. The div contains text elements which I'd like to have evaluated within the current $scope of the ng-view tree. How do I get Angular to re-evaluate the attached element within that scope?

The div element exists initially in a separate part of the document, outside of the ng-view element, and looks something like this:

<div id="eventInfo">
  The event takes place at {{eventModel.startTime}}.
</div>

I need the eventModel.startTime expression to get bound with respect to the scope of the element within the ng-view that I'm moving it into, where its scope contains the correct instance of the eventModel object.

I think I need to do something along these lines:

targetDiv.appendChild(eventInfo);      // Move event text into target element
var scope = angular.element(targetDiv).scope();    // Get target scope
angular.$compile(eventInfo)(scope);    // (?) Apply target scope to event text

The problem is the last line. This JS code is not within an Angular controller, so how do I get access to $compile ?

(I've looked at question " Bind an externally loaded DOM element to Angular's scope " already, but it does not answer my question.)

You would need to get the $compile service from the app injector .

Assuming your ng-app is on the html level, or you manually bootstrapped the app with document as the rootElement you would do (otherwise select which ever is the root element instead of document):

var $compile = angular.element(document).injector().get('$compile');
$compile(eventInfo)(scope);
scope.$apply();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM