1
 $scope.data="<h2>here we have text boxes and button</h2><button type='button' class='btn btn-primary'>inside Basic</button>"+"<button type='button' class='btn btn-primary'>inside Primary</button>"+" Name inside<input type='text' name='namein' /><br>Age indise :: <input type='text' name='agein' /><br></form>"; 

<div ng-bind-html="data"></div>  

This is the content I have used in ng-bind-html, but, it doesn't display text box and button.I have tried same code in plunker but it did not work there.

Rahul Gopi
  • 414
  • 1
  • 16
  • 31
Keshav
  • 821
  • 2
  • 12
  • 33

1 Answers1

2

You need to add $sce.trustAsHtml because a button (like many others elements) is not a trusted element angular can bind without that:

JSFiddle

angular.module('myApp', [])
.controller('dummy', ['$scope', '$sce', function ($scope, $sce) {
    $scope.data = $sce.trustAsHtml('<button type="button" class="btn btn-primary">a new button!</button>');
}]);

If you need to use Angular function inside the ng-bind-html so you need a directive like this (credits):

.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() { return (parsed(scope) || '').toString(); }

            //Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  //The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }         
    }
});

HTML:

<div ng-bind-html="data" compile-template></div>

With $compile you can tell to compile the string to be used as HTML written directly in the view.

Community
  • 1
  • 1
michelem
  • 14,430
  • 5
  • 50
  • 66
  • 1
    But when we add ng-click="showName()" on the button then its not working.Will you please help me around this issue. – Keshav Aug 13 '15 at 11:15
  • Because that's not the way to do it. Use ng-if if you need to add/remove portion of html – michelem Aug 13 '15 at 11:17
  • 1
    But if the html code is provided by back end api then how can we use ng-if in this case. – Keshav Aug 13 '15 at 11:19
  • Edited answer with the directive you should use. – michelem Aug 13 '15 at 11:26
  • 1
    Its working fine but one more question If we want to access content of text box inside ng-bind-html outside ng-bind-html on click of any button then how will we do it?? – Keshav Aug 13 '15 at 12:03
  • Sorry can't understand, please write another question or edit yours with relative code. Then if this answer solved your initial problem you should accept it. – michelem Aug 13 '15 at 13:20
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/86955/discussion-between-keshav-and-michelem). – Keshav Aug 14 '15 at 05:58