What is the best way to catch and format the \"\\n\\n\" inside of text being passed from the server to display line breaks? Fiddle is here: http://jsfiddle.net/nicktest2222/2vYB
Angular 1.2 removed ng-bind-html-unsafe
so here's an updated solution.
The HTML:
<p ng-bind-html="data[0].terms | nl2br"></p>
And the JS:
.filter('nl2br', function ($sce) {
return function (text) {
return text ? $sce.trustAsHtml(text.replace(/\n/g, '<br/>')) : '';
};
})
You have the following options:
pre
tag and keep \n
white-space:pre
css rule and keep \n
\n
with <br>
tag as @sza offered.You can use ngBindHtmlUnsafe directive, with terms: '... <br/><br/>...'
<p ng-bind-html-unsafe='data[0].terms'></p>
You can either send the html to the AngularJS, or send the string with \n
and replace it with <br/>
in AngularJS's controller. Either way should work. Hope it helps.
Demo
You can create a simple filter that will split your string into paragraphs:
.filter('lines', function() {
return function(text) {
return angular.isString(text) ? text.split(/\n/g) : text;
}
})
And use it in view to display them:
<p ng-repeat="paragraph in myText | lines track by $index">{{ paragraph }}</p>
There is no need for bind-html-unsafe
.
See this in action in the snippet:
angular.module('module', [])
.filter('lines', function() {
return function(text) {
return angular.isString(text) ? text.split(/\n/g) : text;
}
})
.controller('MyCtrl', function($scope) {
$scope.myText = "First line\nSecondLine\nThird line\n\n\n\n\nAlone line";
});
p {
min-height: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="module">
<div ng-controller="MyCtrl">
<p ng-repeat="paragraph in myText | lines track by $index">{{ paragraph }}</p>
</div>
</div>
This is not my idea but I can't find the source right now
If 'text' is null it returns an error, I added:
.filter('nl2br', function(){
return function(text){
return text?text.replace(/\n/g, '<br/>'):'';
};
});
You can also use a custom filter to replace \n
to <br>
.
<p ng-bind-html-unsafe="data[0].terms | nl2br"></p>
And the filter.
angular.module('myApp', [])
.filter('nl2br', function(){
return function(text) {
return text ? text.replace(/\n/g, '<br>') : '';
};
});
** EDIT/UPDATE - 2014-12-10 **
Since new versions of Angular removed ng-bind-html-unsafe
@Tamlyn answer is now the best answer. I just changed the way $sce
got injected into the function for speed purpose.
HTML
<p ng-bind-html="data[0].terms | nl2br"></p>
JS
.filter('nl2br', ['$sce', function ($sce) {
return function (text) {
return text ? $sce.trustAsHtml(text.replace(/\n/g, '<br/>')) : '';
};
}]);
jsFiddle