为什么不显示 HTML

Why this doesn't display HTML

在我的 angular 应用程序中,在我检索的数据中,有一些文本可能包含换行符、链接和其他我需要转换为 HTML 的内容。所以我实现了这个函数 "convert" 那些字符串到 html:

$scope.textToHTML = function(text){
    if(!text){return "";}
    var html = text.replace("\r\n", "<br>")// Windows line break
        .replace("\n", "<br>")// Carriage Return
        .replace("\r", "<br>")// Line feed
        .replace("\t", "<span style=\"margin-left: 20px;\"></span>")
        .replace("(https?:\/\/[^\s]*)", "<a href=\"\" target=\"_blank\"></a>");

    return $sce.trustAsHtml(html); 
}

然后我这样使用它: <p data-ng-bind-html="">{{textToHTML(company.description)}}</p>.

当我删除 data-ng-bind-html 时,我看到了预期的代码(已转义),但有了它,我的 <p> 始终是空的。我阅读了 Angular $sce 文档,但我一定遗漏了一些东西,因为我仍然不太明白 trustAs() 做什么...

它是否应该 return 一种带有可以安全解释的代码的字符串? 或者应该说 angular "this string is safe, if you see it in an data-ng-bind-html attribute display it as if !"

ngBindHtml 的正确用法是:

<p data-ng-bind-html="textToHTML(company.description)"></p>