7

I'm trying to get AngularJS and/or HTML to print out the following on 2 separate lines:

FOO
BAR

But my following HTML and JS are showing it on the same line despite my newline \n.

HTML

<div ng-controller="MyCtrl">
  {{name}}!
</div>

JavaScript

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.name = 'FOO \n BAR';
}

Is this possible?

JSFiddle

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • thanks, Casey. So a `filter` is my only option then... I was hoping it'd be less work. – Kevin Meredith Jul 15 '14 at 13:22
  • A filter is kinda useless... Just inject some HTML and use the ng-bind-html directive. – enguerranws Jul 15 '14 at 13:43
  • The question is incorrectly marked as an exact duplicate of an existing question. By using the CSS white-space property, you can display newline characters without adding any HTML tags.

    ,
    or

    – Vlad Lego Feb 07 '18 at 13:08
  • This should be a duplicate of [Preserve line breaks in angularjs](https://stackoverflow.com/questions/19684708/preserve-line-breaks-in-angularjs) – Ivar Aug 07 '19 at 11:02

2 Answers2

3

You can simply use a <br> :

JS

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
   $scope.name = 'FOO <br> BAR';
}

HTML

<div ng-controller="MyCtrl">
  <span class="name" ng-bind-html-unsafe="name"></span>!
</div>

More doc about the ng-bind-html directive : https://docs.angularjs.org/api/ng/directive/ngBindHtml

enguerranws
  • 8,087
  • 8
  • 49
  • 97
-1

In HTML all line break, tab and space are ignored. If you want to insert a new line. use <br/> instead

Bob Yuan
  • 588
  • 3
  • 14
  • 1
    not true in `` or `
    `
    – charlietfl Jul 15 '14 at 13:35
  • Not right. Angular expression ignore newline character and trims white spaces by default. Refer answer at http://stackoverflow.com/questions/29695414/why-white-space-are-getting-ignored-in-angularjs-application – Vineet Kapoor Apr 23 '16 at 17:19