Question

Say I have an element like this:

<elemental></elemental>

I can pull the scope by running:

angular.element($('elemental')).scope()

Is it possible to get an element's source template after it's been compiled in a similar fashion from the DOM?

Was it helpful?

Solution

It is possible although I would think the use case for this should be pretty rare (i.e. your code is running outside the Angular "world"). I've given the directive an ID with the same name so I could locate it via the DOM, but this could be done using any DOM element that is part of the app:

var appElement = angular.element(document.getElementById('elemental'));
var injector = appElement.injector();
var myTemplate = injector.get('elementalDirective')[0].template;
console.log(myTemplate);    // the template

First, get the app's injector. Then locate the provider for the custom directive, which will always be the name of the directive plus the string 'Directive' (in this case elementalDirective). Then access the template property.

Demo: Here is a fiddle

See also: Call Angular JS from legacy code


Edit: My previous answer assumed the element was not compiled yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top