0

I'm in a bit of a jam, I am getting data from an endpoint with angular, JSON, and sometimes that data could be HTML code, I read about it and I found out that if I want to parse that info as HTML, without "", I have to use JSON.parse().

The problem is that now the code is escaped and throws an error before calling it in my template. http://screencast.com/t/zledZ6rBod

I can see why this is happening, but how can I output interpretable HTML markup in my template?

4
  • I tried to use $sce.parseAs($sce.HTML, myJSONResponse.HTMLcontent) Another error. screencast.com/t/fdoiIEveMJ Commented Sep 11, 2013 at 12:24
  • Also tried with trustAsHtml: $scope.projContent = $sce.trustAsHtml(data[i].posts[0].content); Commented Sep 11, 2013 at 12:26
  • please post your client side code Commented Mar 25, 2014 at 10:45
  • I forgot to close this question :), it's from last year :). I'll post the answer in a jiffy. Commented Mar 25, 2014 at 13:30

2 Answers 2

1

I think there is a simpler way to 'sanitize' an HTML string.

  1. Import angular-sanitize.min.js into your HTML.
  2. Add it as a dependency var app = angular.module('myapp', ['ngSanitize']);
  3. Then use ng-bind-html="HTML_STRING_VAR_HERE"

This way you don't have to make a function to sanitize and you can pass the variable directly.

You can see an example in this plunker. http://plnkr.co/edit/4FBUSooNMpqk1rYAZYdZ
Let me know what you think.

Sign up to request clarification or add additional context in comments.

Comments

0

The answer is using $sce, Strict Contextual Escaping, here are the docs: http://docs.angularjs.org/api/ng/service/$sce#methods_trustashtml

for me it worked doing it like this:

In the controller:

$scope.theHtml = '<div class="red">Content</div>'; $scope.parseHtml = function() { return $sce.trustAsHtml($scope.theHtml); };

In the template:

<div ng-bind-html="parseHtml()"></div>

Comments

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.