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

2019-07-26 10:12发布

问题:

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

回答1:

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>


回答2:

ng-bind-html does what it says on the tin: it binds html. It doesn't bind angular template code into your dom.

You need to do this instead:

$scope.thisCanBeusedInsideNgBindHtml = 
    $sce.trustAsHtml("<div>"+$sanitize(name)+"</div>");

To do this you'll want to include the module ngSanitize from the javascript angular-sanitize.js. See https://docs.angularjs.org/api/ngSanitize

If you want to insert some html that includes angular directives then you should write your own custom directive to do it.



回答3:

In your html just use {{name}} The {{var}} notation is to be used in the HTML code to evaluate that variable.



回答4:

You can do :

$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml('<div ng-bind="name"></div>');


回答5:

Sorry I make another answer.

If you have

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

Then you can do

var str = "<div>{{name}}</div>";
var output = str.replace('{{name}}', $scope.name);

It seems to be the only option.