ng-bind-html does not display form component like textbox,button

1.8k Views Asked by At
 $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.

1

There are 1 best solutions below

7
On

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.