AngularJs - html 渲染
AngularJs - html rendering
我们使用弹性搜索高亮器,从高亮器中获取以下代码。
<span style='font-weight:bold;color:red;'>Baskar</span> Test
我们在html中显示结果如下。
<tr
ng-repeat="result in searchModelResult">
<td><p ng-bind-html="result.name"></p></td>
</tr>
我在 angular 模块中包含了 sanitize.js 和 ngSanitize。我仍然没有看到 html 效果,如红色字体和粗体字体。
我遗漏了什么吗?
谢谢,
Baskar.S
您需要删除第二个绑定表达式:
{{result.name}}
它似乎正在覆盖来自 ng-bind-html
的绑定,默认绑定将 HTML 转义字符串。
你需要做两件事,首先移除
{{result.name}}
正如 Daniel 所说...那么您需要对 angular 说要相信您控制器中的 html:
myApp.controller('MyCtrl', function ($scope, $sce) {
$scope.result.name = $sce.trustAsHtml('<span style="font-weight:bold; color:red;">Baskar</span> Test');
});
您可以查看$sce的完整文档here
如果您需要在 ng-repeat 中迭代,您可以创建一个过滤器:
myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
然后在视图中使用它:
<tr ng-repeat="result in searchModelResult">
<td><p ng-bind-html="result.name | unsafe"></p></td>
</tr>
我们使用弹性搜索高亮器,从高亮器中获取以下代码。
<span style='font-weight:bold;color:red;'>Baskar</span> Test
我们在html中显示结果如下。
<tr
ng-repeat="result in searchModelResult">
<td><p ng-bind-html="result.name"></p></td>
</tr>
我在 angular 模块中包含了 sanitize.js 和 ngSanitize。我仍然没有看到 html 效果,如红色字体和粗体字体。
我遗漏了什么吗?
谢谢, Baskar.S
您需要删除第二个绑定表达式:
{{result.name}}
它似乎正在覆盖来自 ng-bind-html
的绑定,默认绑定将 HTML 转义字符串。
你需要做两件事,首先移除
{{result.name}}
正如 Daniel 所说...那么您需要对 angular 说要相信您控制器中的 html:
myApp.controller('MyCtrl', function ($scope, $sce) {
$scope.result.name = $sce.trustAsHtml('<span style="font-weight:bold; color:red;">Baskar</span> Test');
});
您可以查看$sce的完整文档here
如果您需要在 ng-repeat 中迭代,您可以创建一个过滤器:
myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
然后在视图中使用它:
<tr ng-repeat="result in searchModelResult">
<td><p ng-bind-html="result.name | unsafe"></p></td>
</tr>