How to Render HTML Value in Ng-repeat in AngularJS?

By Hardik Savani October 20, 2023 Category : jQuery Angular

I always post small example of AngularJS function, In this example we learn how to render our HTML code in ng-repeat using trustashtml filter.

Sometimes we have array or object of records with html values, at that time we require to use ng-repeat, But we can't simple way render html code, we should require to use trustashtml or ng-bind-html-unsafe etc. So in this example i created one filter for this task using sce trustashtml. filter as like bellow you can see code of that filter using $sce.trustAsHtml.

Filter

app.filter('trustAsHtml',['$sce', function($sce) {

return function(text) {

return $sce.trustAsHtml(text);

};

}]);

I will give you full example of render html code in ng-repeat using bellow angular filter, so let's see bellow example:

Example

<!DOCTYPE html>

<html>

<head>

<title>AngularJS - How to render HTML value in ng-repeat ?</title>

<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

</head>

<body>


<div class="container" ng-app="mainApp" ng-controller="myController" id="mainController">

<ul>

<li ng-repeat="item in data">

{{ item.title }}

<br/>

<div ng-bind-html="item.description|trustAsHtml">

</div>

</li>

</ul>

</div>


<script type="text/javascript">

var app = angular.module("mainApp", []);

app.controller('myController', function($scope, $timeout) {


$scope.data = [

{title:'Title 1', description:'<h1>Test for it</h1>'},

{title:'Title 2', description:'<strong>Here is bold</strong>'},

{title:'Title 3', description:'It is normal'},

];


});


app.filter('trustAsHtml',['$sce', function($sce) {

return function(text) {

return $sce.trustAsHtml(text);

};

}]);


</script>


</body>

</html>

I hope it can help you...

Shares