Skip to content Skip to sidebar Skip to footer

Preserving Line Breaks In Angularjs

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:

Solution 1:

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:

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

Angular 1.2+:

<codeng-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:

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

Angular 1.2 version, using $sce:

functionTodoCtrl($scope, $sce) {
  $scope.lines = $sce.trustAsHtml('var x=1;<br />var y=2;');
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app><divng-controller="TodoCtrl"><p>Working version: </p><codeng-bind-html="lines"></code><p>Original version: </p><code>{{lines}}</code></div></div>

Solution 2:

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+

Post a Comment for "Preserving Line Breaks In Angularjs"