我试图在控制器中清理HTML,因为我试图使用帖子的标题动态更新document.title。 (我知道出于搜索引擎优化的目的,我们不推荐使用它,但我需要在这里使用它)
$scope.prevTitle = "dynamic title gets pulled in here &"
document.title = $scope.prevTitle
对于这个例子,我只是使用了一个随机的HTML实体。我已经尝试了official documentation中的parseAsHtml方法,但我没有运气。我尝试了以下方法:
document.title = $sce.parseAsHtml($scope.prevTitle)
但没有运气。文档表明它需要在函数中使用。关于我如何实现这一点的任何建议?
上面的控制台日志(console.log($ sce.parseAsHtml($ scope.prevTitle)))会返回:
function (b,c){return e.getTrusted(a,d(b,c))}
答案 0 :(得分:2)
$sanitize
可以用作@acg指出。或者,您可以直接将它与ng-bind-html
指令一起使用,它会在呈现输出之前自动清理输出变量。
上面的观点在documentation中并不十分清楚,但是有一个相当广泛的例子,你可以用它来玩。
另请注意,ngSanitize
是一个外部模块,您需要明确加载angular-sanitize.js
或将其包含在您的js缩小中。
答案 1 :(得分:1)
使用$ sanitize和trustAsHtml代替
首先注入' ngSanitize'在你的模块中
现在在您的控制器中,只需添加
$scope.prevTitle = "dynamic title gets pulled in here &"
document.title = $sce.trustAsHtml($scope.prevTitle)
答案 2 :(得分:0)
如果你想清理返回的html,我认为它就像使用$sanitize服务一样简单:
document.title = $sanitize($sce.parseAsHtml($scope.prevTitle))