I think I've finally solved this issue. I hope this answer will help someone.
As I mentioned earlier this is a 3-steps process.
- Escape HTML inclusions in initial text.
- Apply filter to break multiline text to paragraphs.
- Output text without further escaping.
For the first step I were trying to find some existing function to escape initial text, but to no avail. Seems like AngularJS is not exposing any methods of doing this (please correct me if I'm wrong). Finally I've created my own filter to escape HTML:
myModule.filter('htmlEscape', function() {
return function(input) {
if (!input) {
return '';
}
return input.
replace(/&/g, '&').
replace(/</g, '<').
replace(/>/g, '>').
replace(/'/g, ''').
replace(/"/g, '"')
;
};
});
Then I've created a filter to break plain text into paragraphs:
myModule.filter('textToHtml', ['$sce', 'htmlEscapeFilter', function($sce, htmlEscapeFilter) {
return function(input) {
if (!input) {
return '';
}
input = htmlEscapeFilter(input);
var output = '';
$.each(input.split("\n\n"), function(key, paragraph) {
output += '<p>' + paragraph + '</p>';
});
return $sce.trustAsHtml(output);
};
}])
I'm injecting early created htmlEscape
filter to it and using $sce.trustAsHtml
method to return value suitable for use with ng-bind-html
directive.
And in the end I'm invoking this filter in the partial template like this:
<div ng-bind-html="someText|textToHtml"></div>
Here's the result: