AngularJS – How to render HTML value in ng-repeat ?

In AngularJS, you can use the ng-repeat directive to render HTML values dynamically. However, it’s important to be cautious when rendering HTML content dynamically, as it can expose your application to security vulnerabilities like Cross-Site Scripting (XSS) attacks if not handled properly.

Html Structure:-

<!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:'Roshan 1', description:'<h1>Test for it</h1>'},
      {title:'Roshan 2', description:'<strong>Here is bold</strong>'},
      {title:'Roshan 3', description:'It is normal'},
    ];


  });


  app.filter('trustAsHtml',['$sce', function($sce) {
    return function(text) {
      return $sce.trustAsHtml(text);
    };
  }]);


</script>


</body>
</html>

Output:-

Hopefully, It will help you ..!!!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x