How to Render HTML Value in Ng-repeat in AngularJS?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- AngularJS Convert Comma Separated String to Array Example
- AngularJS - How to Create Read More/Less Toggle using Directive?
- AngularJS Nl2br Filter for Textarea Content Example
- AngularJS Display Default Image If Original Does Not Exists Example
- How to Call AngularJS Controller Function in JQuery?
- AngularJS Image Upload with Preview Example
- How to Call Function on Page Load in AngularJS?
- AngularJS Pagination using dirPagination Directive Example
- AngularJS Tooltip using UI Bootstrap tpls HTML Example
- AngularJS Simple Datepicker Directive Example Tutorial
- AngularJS Sorting(using Orderby Filter) Table Data Example
- AngularJS - How to Limit String Length using Filter?
- AngularJS - How to Capitalize the First Letter of Word Example
- How to Remove HTML Tags from String in AngularJS?