0

I have an Angular app that needs to support customizable reporting. My intention is to allow the user to select one of many reports available and have a back end REST api provide the template and the data as JSON (end user can customize the template).

The app would then insert the template somehow into a "reporting" view page then put the data in the scope and Angular should compile and display the report / template.

I've looked into ng-include however that seems to support only an URL or path to a document, however I have the template text already via the REST service and I cannot use static urls or file paths, this needs to be via REST api, if ng-include accepted the template text directly that might work but it doesn't.

I've tried writing a directive, trying to call a method on the page (getTemplate()) that would load the template already fetched from the scope however my directive doesn't have access to the scope apparently.

What tactic should I use to accomplish this? A directive seems best but I'm obviously doing it wrong and completely lost in the docs and my many attempts trying to accomplish this.

2 Answers 2

1

You could compile the dynamic template to an element on the DOM in a controller and then in the controller have something like this:

var el = angular.element('#myselector');   
el.html(mydynamichtmlfromresource);

$compile(el.contents())($scope);

I would setup your route with template with single DIV container (you could pull all the static container template in a single JavaScript file using HTMLToJS online tool or grunt task):

<section class="view">
  <div id="myselector"></div>
</section>
Sign up to request clarification or add additional context in comments.

Comments

1

I've tried writing a directive, trying to call a method on the page (getTemplate()) that would load the template already fetched from the scope however my directive doesn't have access to the scope apparently.

Yes you are right, but there is a way to pass data from scope to directive. lets say you want to pass a var "x" from scope to directive use this

<directive directiveVar='x'/>

inside directive, you need to use isolated scope

 "scope": {
                    "directiveVar": "="
                },

this variable will be available only in controller and postlink function, so your directive template needs to be like this

<ng-bind-html="directiveVar"/>

inside the postlink you may need to use this code snippet

$scope.directiveVar =$sce.trustAsHtml($scope.directiveVar)

References

  1. http://docs.angularjs.org/api/ng.directive:ngBindHtml
  2. http://docs.angularjs.org/api/ng.$compile

1 Comment

I'll try this, thank you, missed ngBindHtml before now.

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.