AngularJS using $sce.trustAsHtml with ng-repeat
Asked Answered
K

2

14

I'm trying to use $sce.trustAsHtml() with a property of an object in ng-repeat. The result is that the HTML is totally blank. The HTML outputs correctly using ngSanitize though.

<div ng-repeat="question in questions">
    <p ng-bind-html="$sce.trustAsHtml(question.body)">
    </p>
</div>

I'm on AngularJS v1.3.0-beta.3 by the way. Not sure if there's a bug or I do something wrong.

Koumis answered 27/6, 2014 at 19:8 Comment(0)
B
29

You can't use $sce.trustAsHtml in an expression (unless $sce is a property on the $scope) because expressions are evaluated in the context of the $scope.

The cleanest approach is to use ngSanitize.
The second cleanest is to expose $sce.trustAsHtml as a function in the $scope:

<div ng-repeat="...">
    <p ng-bind-html="trustAsHtml(question.body)"></p>
</div>

$scope.trustAsHtml = $sce.trustAsHtml;
Batholith answered 27/6, 2014 at 19:37 Comment(4)
Thanks for explanation. Had trouble using $sce in services - worked only in filters and directivesMaddux
This was exactly what I was looking for and it's short, simple and sweet. Thanks!Delinda
How about using $sce.trustAsHtml(questions) in controller and use only <p ng-bind-html="question.body"></p>. ?Fabio
@HardikMishra, that's also possible (and better than putting it in the template).Batholith
C
15

OR have a filter:

angular.module('myApp')
    .filter("sanitize", ['$sce', function($sce) {
        return function(htmlCode){
            return $sce.trustAsHtml(htmlCode);
        }
}]);

in html:

<div ng-bind-html="question.body | sanitize"></div>
Clinometer answered 5/2, 2015 at 11:49 Comment(1)
It does not sanitize htmlCode for meCocklebur

© 2022 - 2024 — McMap. All rights reserved.