2

Essentially what I am doing is requesting a template from my server. A short example of this looks something like this:

$scope.template = {
  'title': 'default',
  'description': 'default template',
  'html': '<html><head><style>body {background: red;}</style></head><body>{{data.name}}</body></html>'
}

$scope.data = {
  name: 'John'
}

This is the JSON object I am receiving from my server. I want to render this into the DOM. What would show up, is just what is store in $scope.name.

I have this in my angular

app.filter("trust", ['$sce', function($sce) {
  return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  };
}]);

And this in my HTML

<div ng-bind-html="template.html | trust"></div>

This renders the html, but leaves {{name}} as {{name}}, when it should say John.

3

2 Answers 2

3

Storing html (with angular variables) in the backend is bad practice. Your priority should be to refactor your backend code.

If you don't have access to the backend you can try to create a directive that uses $compile:

$scope.template = $compile('<html><head><style>body {background: red;}</style></head><body>{{data.name}}')($scope);

You can do that in a controller as well using $interpolate:

$scope.template = $interpolate('<html><head><style>body {background: red;}</style></head><body>{{data.name}}')($scope);
Sign up to request clarification or add additional context in comments.

3 Comments

I'm building the backend too, which is in Node. How would you suggest refactoring backend code? For this, I was trying to make a fast way to switch templates. Would you use something like jade?
A backend should only return data. The formatting is done client side using angularjs templating.
Right, I'm wanting to store my templates in the backend becasue they should dynamically show depending on the user. All of these templates are going to show the same data, but just in different formats.
0

it seems you forgot in $scope.data to put name in single quotes, like this:

$scope.data = {
  'name' = 'John'
}

Hope this works

1 Comment

As mentioned below, that was an error in me simplifying the question, not the actual code. I've updated the question.

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.