tompave
tompave

Reputation: 12412

Initialize ng-app after document is loaded

I'm working with AngularJS.

One of the (technical) requirements is to fetch the "ng enabled" HTML content from the server, in response to a click event, and inject it into a <div ng-app> via JavaScript.

The problem is that the newly injected HTML is not wired, as Angular goes through the compile and link phases only when the page is loaded the first time.

Is there a way to trigger them manually?
Am I approaching this problem in the wrong way? Is there a more idiomatic way to accomplish what I described?

Thanks

Upvotes: 0

Views: 100

Answers (2)

Chandermani
Chandermani

Reputation: 42669

There are multiple ways to inject dynamic content into the view in AngularJS. One of the way to inject dynamic content is to use ng-include directive. It can take an endpoint from where to get view. You can combine it with ng-if to achieve load view on click. For example:

<span ng-if="clicked">
   <div ng-include='pathToTheHtml'></div>
</span>

The clicked variable would be false first, on clicking on the button set it to true, this would trigger ng-include to get the content and inject it into html.

If you want finer control then you need to use the $compile service. The html that needs to be injected into the DOM needs to be compiled and linked to the scope using $compile service. This can be done in a directive.

element.append($compile(htmlFragment)(scope))

Upvotes: 2

Related Questions