Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS using $sce.trustAsHtml with ng-repeat

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.

like image 543
ZoM Avatar asked Jun 27 '14 19:06

ZoM


People also ask

What is SCE trustAsHtml in AngularJS?

The ng-controller uses $sce (Strict Contextual Escaping) service which is used to mark the HTML as trusted using the trustAsHtml method. Note: Unless the HTML content is trusted using the $sce service, it will not be displayed using ng-bind-html directive.

How do you condition in NG-repeat?

You can add condition using ng-if also and this is effective too. You can apply any condition to your list using ng-if attribute. In below example, I have put condition where Age > 20 and IsActive is true. ng-repeat will fetch all records which full fill this scenario.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What does this directive do in AngularJS does ng-repeat?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.


2 Answers

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;
like image 110
gkalpak Avatar answered Oct 16 '22 21:10

gkalpak


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>
like image 20
Moin Haidar Avatar answered Oct 16 '22 23:10

Moin Haidar