angularjs newline filter with no other html
I'm trying to convert newline characters (\n
) to html br
's.
As per this discussion in the Google Group, here's what I've got:
myApp.filter('newlines', function () {
return function(text) {
return text.replace(/\n/g, '<br/>');
}
});
The discussion there also advises to use the following in the view:
{{ dataFromModel | newline | html }}
This seems to be using the old html
filter, whereas now we're supposed to use the ng-bind-html
attribute.
Regardless, this poses a problem: I don't want any HTML from the original string (dataFromModel
) to be rendered as HTML; only the br
's.
For example, given the following string:
While 7 > 5
I still don't want html & stuff in here...
I'd want it to output:
While 7 > 5<br>I still don't want html & stuff in here...
Is there any way to accomplish this?
Maybe you can achieve this only with html, a <preformated text>
way ? It will avoid from using filters or do any kind of processing.
All you have to do is display the text within an element that has this CSS:
<p style="white-space: pre;">{{ MyMultiLineText}}</p>
This will parse and display \n as new lines. Works great for me.
Here, a jsFiddle example.
Instead of messing with new directives, I decided to just use 2 filters:
App.filter('newlines', function () {
return function(text) {
return text.replace(/\n/g, '<br/>');
}
})
.filter('noHTML', function () {
return function(text) {
return text
.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<');
}
});
Then, in my view, I pipe one into the other:
<span ng-bind-html-unsafe="dataFromModel | noHTML | newlines"></span>
A simpler way to do this is to make a filter that splits the text at each \n
into a list, and then to use `ng-repeat.
The filter:
App.filter('newlines', function() {
return function(text) {
return text.split(/\n/g);
};
});
and in the html:
<span ng-repeat="line in (text | newlines) track by $index">
<p> {{line}}</p>
<br>
</span>