Saving line breaks in AngularJS

I am working on an application using AngularJS. My controller looks like this:

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

My view is as follows:

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

When a view is rendered, the value in $scope.lines displayed on a single line as follows:

 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 to <br /> , however that didn't work either.

+5
source share
2 answers

So far, the only way to do this would be to use ng-bind-html ( -unsafe ) (check the version of angular because you might need to use $sce ) to bind the HTML to the element, for example:


Angular 1.0.X:

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

Angular 1.2 +:

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

but he needs $sce :

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

And of course, use 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 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> 
+3
source

your $ scope.lines are replaced as a simple line. you have to bind it as html.

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

0
source

Source: https://habr.com/ru/post/1206348/


All Articles