Parshuram Parshuram - 15 days ago 7
AngularJS Question

ng-bind-html not working with my $scope.variable

I am trying to add something like dynamic HTML using ng-bind-html but its not working with $scope variable

Here is my Angular code

1)My controller

$scope.name = "Parshuram"
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");


Also that my string is dynamic

"<div><table class=" + "\"table table - bordered table - responsive table - hover add - lineheight table_scroll\"" + "><thead><tr><td>Name</td><td>Age</td></tr></thead><tbody><tr ng-repeat=" + "\"tr in dyna\"" + "><td>{{tr.name}}</td><td>{{tr.age}}</td></tr></tbody></table></div>"


So i cant replace every variable with $scope

2)- My HTML

<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</div>


I got this output

{{name}}


My expected output is

Parshuram


Please can anyone help i am stuck at this point,does that $sce does not bind scope variable?? ..

Answer

I've created a working plnkr here: https://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3?p=preview

the problem is that ng-bind-html is not bound to the scope. you should manually compile the content.

a valid and reusable solution should be creating a directive, whitout using any external modules.

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




<div ng-app="mymodule" ng-controller="myModuleController">
    <div ng-bind-html="thisCanBeusedInsideNgBindHtml" compile-template></div> 
</div>