ng-bind-html 不适用于我的 $scope.variable [英] ng-bind-html not working with my $scope.variable
问题描述
我正在尝试使用 ng-bind-html 添加类似动态 HTML 的内容,但它不适用于 $scope 变量
这是我的 Angular 代码
1)我的控制器
$scope.name = "Parshuram"$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
而且我的字符串是动态的
"<div><table class=" + "\"table table - 带边框的表格 - 响应式表格 - 悬停添加 - lineheight table_scroll\"" + "><thead><tr><td>姓名</td><td>年龄</td></tr></thead><tbody><tr ng-repeat=" + "\"tr in dyna\""+ "><td>{{tr.name}}</td><td>{{tr.age}}</td></tr></tbody></table>;</div>"
所以我不能用 $scope 替换每个变量
2)- 我的 HTML
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
我得到了这个输出
{{name}}
我的预期输出是
帕舒拉姆
请谁能帮我解决这个问题,$sce 没有绑定作用域变量吗??..
我在这里创建了一个有效的 plnkr:https://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3?p=preview
问题是 ng-bind-html 没有绑定到作用域.您应该手动编译内容.
一个有效且可重用的解决方案应该是创建一个指令,不使用任何外部模块.
function compileTemplate($compile, $parse){返回 {链接:功能(范围,元素,属性){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" 编译模板></div>
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?? ..
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>
这篇关于ng-bind-html 不适用于我的 $scope.variable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!