Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

angularjs - 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?? ..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...