我正在尝试使用 ng-bind-html 添加类似动态 HTML 的内容,但它不适用于 $scope 变量
这是我的 Angular 代码
1)我的 Controller
$scope.name = "Parshuram"
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
而且我的字符串是动态的
"<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>"
所以我不能用 $scope 替换每个变量
2)- 我的 HTML
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</div>
我得到了这个输出
{{name}}
我的预期输出是
Parshuram
谁能帮我解决这个问题,$sce 不绑定(bind)作用域变量吗?? ..
最佳答案
我在这里创建了一个工作 plnkr:https://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3?p=preview
问题是 ng-bind-html 没有绑定(bind)到范围。 您应该手动编译内容。
一个有效且可重用的解决方案应该是创建一个指令,而不使用任何外部模块。
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>
关于html - ng-bind-html 不适用于我的 $scope.variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788937/