Sagnik Chakraborti Sagnik Chakraborti - 1 year ago 122
Javascript Question

Angular ng-bind-html on Object Elements

I got the code from another question and it's straightforward and working fine

<div ng-controller="ExampleController">
<p ng-bind-html="testHTML"></p>

(function(angular) {
'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.testHTML =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';


Suppose, I'm getting an object and I want to show an element of the object

$scope.testHTML = obj;

var obj = {
title: 'Title',
description: 'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>'

Then how should I bind only the description on the html end?
I've tried
<p ng-bind-html="{{testHTML.description}}"></p>
<p ng-bind-html="testHTML.description"></p>

plnkr example

Answer Source

Try this snippet to bind HTML

Firstly, you can create custom filter to bind the HTML in AngularJS.

Now, you can use this filter anywhere into the myApp module by just writing yourHTML | html, That will done the job.

var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope','$sce', function($scope, $sce) {
  var obj = {
     title: 'Title',
     description: 'I am an <code>HTML</code>string with ' +
       '<a href="#">links!</a> and other <em>stuff</em>',
     description1: 'I am an <b>HTML</b>string with ' +
       '<a href="#">links!</a> and other <u><b>stuff</b></u>'
  $scope.testHTML = obj;
  //Use $SCE in controller
  var preview_data = obj.description;
  $scope.htmlSafe = $sce.trustAsHtml(preview_data);
//Custom filter (Alternate way)
myApp.filter('html', ['$sce', function ($sce) { 
    return function (text) {
        return $sce.trustAsHtml(text);
<script src=""></script>
<div ng-app="myApp" ng-controller="GreetingController">
  <b>By using custom filter</b>
  <div ng-bind-html="testHTML.description | html"></div>
  <div ng-bind-html="testHTML.description1 | html"></div>

  <b>By using $SCE inside controller</b>
  <div ng-bind-html="htmlSafe"></div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download