Within my angular application, I have data that may contain line breaks, links, and other elements that need to be converted to HTML. To handle this requirement, I created a function that converts the text to 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=\"$1\" target=\"_blank\">$1</a>");
return $sce.trustAsHtml(html);
}
To apply this function, I use it in the following way:
<p data-ng-bind-html="">{{textToHTML(company.description)}}</p>
.
After removing data-ng-bind-html
, I can see the expected code (escaped), but once included, my <p>
element remains empty. I have gone through the Angular $sce documentation, yet I still feel confused about the purpose of trustAs()
...
Does it generate a safe string of code for interpretation? Or does it inform Angular to treat the string as safe when encountered within a data-ng-bind-html attribute?