AngularJS – display html without escaping using ng-bind-html

AngularJS ng-bind-html directive can be used to insert html into an element. Here is sample usage:

<p ng-bind-html="myHTML"></p>

Few points to note:

  1. One need to include ngSanitize in module dependency
  2. Javascript angular-sanitize.js should also be included along with angular.js

Example code:

<style type="text/css">p {background-color:lightgray;}</style>
<div ng-app="myApp" ng-controller='MyCtrl'>
  Server returned<p>{{ajaxHtmlData}}</p>
  How it renders using ng-bind-html<p ng-bind-html="ajaxHtmlData"></p>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-sanitize.js"></script>
<script type="text/javascript">
var module = angular.module('myApp', ['ngSanitize']);
module.controller('MyCtrl', function($scope, $http) {
  $http.get("/api/get-hello-world-with-tags.php")
  .then(function(response) {
      $scope.ajaxHtmlData = response.data;
  });
});
</script>
refresh

Related Links

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments