4

I have a data source that contains an array of raw HTML strings. I must display these in a page to the user.

Being a bit new with Angular, the first thing I tried was this:

<div ng-repeat="html in ctrl.html" ng-bind="html"></div>

This causes Angular to escape my HTML and display it as a string. It isn't what I need, but at least it shows that Angular is, indeed, loading the data.

Doing a Google search, I read about the ng-bind-html-unsafe directive, which I understand is supposed to inject text into an HTML document without escaping or sanitizing it in any way, which is what I want because I must trust our data source.

<div ng-repeat="html in ctrl.html" ng-bind-html-unsafe="html"></div>

This doesn't work, either. It just shows me a blank page. When I open the document inspector, I see that there is a div tag for each entry in the HTML array, but the divs are all blank.

Doing more Google-fu, I found discussions about calling methods on $scope to make Angular play nice with this. They say that ng-bind-html-unsafe is deprecated.

With all the talk about different ways to do what I need with different versions of Angular, how do I do this with today's version: 1.4?

1
  • try to inject $sce to your controller and inject the html with $sce.trustAsHtml Commented Sep 10, 2015 at 15:59

3 Answers 3

6

I think you have to "sanitize" your html's..

Example:

angular.module('sanitizeExample', ['ngSanitize'])
       .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
         this.html = array with your htmls;

         this.sanitizeHtml = function(html) {
           return $sce.trustAsHtml(html);
         };
       }]);

Then

<div ng-repeat="html in ctrl.html" ng-bind-html="ctrl.sanitizeHtml(html)"></div>

I think it will work

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

Comments

1

use ngSanitize module...

var app = angular.module("myApp", ['ngSanitize']);

see this link. this work perfect

Comments

-1

In view

<div ng-repeat="html in ctrl.html" ng-bind-html="ctrl.sanitizeHtml(html)"></div>

In controller

myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

This will work

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.