5

I am working on an app that uses AngularJS. My controller looks like this:

function TestCtrl($scope) {
  $scope.lines = 'var x=1;\nvar y=2;';
}

My view looks like this:

<div ng-controller="TestCtrl">
  <p>
    Output:<br />
    <code>{{lines}}</code>
  </p>
</div>

When the view is rendered, the value in $scope.lines is rendered on a single line like this:

var x=1; var y=2;

However, I want to display it as:

var x=1;
var y=2;

What am I doing wrong? I tried switching \n with <br />, however, that did not work either.

user70192
  • 13,786
  • 51
  • 160
  • 240

2 Answers2

3

So far, the only way to do it would be using ng-bind-html (-unsafe) (check your angular version because you might need to use $sce) to bind HTML to an element, like this:


Angular 1.0.X:

<code ng-bind-html-unsafe="lines"></code>

Angular 1.2+:

<code ng-bind-html="lines"></code>

but it needs $sce:

$scope.lines = $sce.trustAsHtml('var x=1;<br />var y=2;');

And of course, use the HTML line break: <br />

Here is a working example: http://jsfiddle.net/3fha088t/

Same example here as a snippet:

function TodoCtrl($scope) {
  $scope.lines = 'var x=1;<br />var y=2;';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-app>
  <div ng-controller="TodoCtrl">
      <p>Working version: </p>
        <code ng-bind-html-unsafe="lines"></code>
      <p>Original version: </p>
      <code>{{lines}}</code>
  </div>
</div>

Angular 1.2 version, using $sce:

function TodoCtrl($scope, $sce) {
  $scope.lines = $sce.trustAsHtml('var x=1;<br />var y=2;');
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="TodoCtrl">
      <p>Working version: </p>
        <code ng-bind-html="lines"></code>
      <p>Original version: </p>
      <code>{{lines}}</code>
  </div>
</div>
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • If you are using /n as in the original question, it's likely that @JimmyRare's solution of adding "white-space: pre;" to the css will fix this – Ben Taliadoros Feb 21 '17 at 10:22
  • @BenTaliadoros Yeah, but it's usually a good idea to stick to one way of making line breaks. Since OP is already using `
    ` in his view (rather than `
    content
    `), he should probably stick with HTML line breaks.
    – Shomz Feb 21 '17 at 15:12
0

your $scope.lines are replaced as plain string. you should bind it as html instead.

see this How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Community
  • 1
  • 1
Rabi
  • 2,210
  • 17
  • 18