There seems to be an issue with HTML, not Angular. Angular is simply outputting what you have instructed it to display.
In HTML, unless within a <pre>
tag, continuous whitespace (such as returns, tabs, and spaces) is condensed into a single space. This is why special elements like <br/>
and
are necessary outside of a <pre>
block.
To better understand the concept, try this snippet in HTML:
<h3>Basic DIV</h3>
<div>
Some
text
here
</div>
<h3>With Non-Breaking Spaces and Line Breaks</h3>
<div>
Some<br/>
text<br/>
here<br/>
</div>
<h3>Utilizing a PRE Tag</h3>
<pre>
Some
text
here
</pre>
Here's a Fiddle that showcases the above demonstration.
If you wish to avoid using the <pre>
tag and still achieve similar formatting, you'll need to style the content accordingly since most default styles for <pre>
utilize fixed-width fonts like Courier or Consolas.
Alternatively, you could create an Angular filter that processes spaces, tabs, and line breaks into appropriate markup, although this may require regular maintenance.
EDIT: Angular Solution Based on Above Understanding
The optimal solution, in my opinion, is to develop a filter that cleanses the text and formats it with line breaks and non-breaking spaces.
Consider this approach
app.filter('formatText', function (){
return function(input) {
if(!input) return input;
var output = input
// Replace potential line breaks.
.replace(/(\r\n|\r|\n)/g, '<br/>')
// Replace tabs.
.replace(/\t/g, ' ')
// Amend spaces.
.replace(/ /g, ' ');
return output;
};
});
To implement this filter, use the following method:
<span ng-bind-html="foo | formatText"></span>
Key Points to Remember:
- Include the
angular-sanitize.js
file in your scripts section.
- Declare
'ngSanitize'
within your module:
var app = angular.module('myApp', ['ngSanitize']);
This step enables the use of directives such as ng-bind-html
or ng-bind-html-unsafe
.
Here is a plunk demonstrating how to implement this filter.