Par*_*tte 2 html sanitize angularjs ng-bind-html
我正在尝试使用 ng-bind-html 添加类似动态 HTML 的内容,但它不适用于 $scope 变量
这是我的 Angular 代码
1)我的控制器
$scope.name = "Parshuram"
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Run Code Online (Sandbox Code Playgroud)
另外我的字符串是动态的
"<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>"
Run Code Online (Sandbox Code Playgroud)
所以我不能用 $scope 替换每个变量
2)- 我的 HTML
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我得到了这个输出
{{name}}
Run Code Online (Sandbox Code Playgroud)
我的预期输出是
Parshuram
Run Code Online (Sandbox Code Playgroud)
请任何人都可以帮助我卡在这一点上,$sce 没有绑定作用域变量吗??..
我在这里创建了一个工作 plnkr:https ://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3 ? p = preview
问题是 ng-bind-html 没有绑定到范围。您应该手动编译内容。
一个有效且可重用的解决方案应该是创建一个指令,不使用任何外部模块。
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>
Run Code Online (Sandbox Code Playgroud)