简体   繁体   中英

line break in a string js

I have something like notification if I deleted a row in a table. I am actually using angularjs, so it is inside a ngcontroller function. I have a label in my html that will display a message which is initialize inside my ngcontroller. Like this,

if(response.deleted!=''){
    $scope.msg=response.deleted+' has not been deleted successfully.';
}
if(response.undeleted!=''){
    $scope.msg2=response.undeleted+' has not been deleted.';
}
$('.error2').text($scope.msg+'\n'+$scope.msg2); 

I want the two messages separated by a new line, however nothing happens. And if I replace the \\n with <br> , it actually prints out the <br> . What will I do to solve this?

Short asnwer:

$('.error2').html($scope.msg+'<br>'+$scope.msg2); 

Demo:

 // temporary duck $scope = {}; $scope.msg = 'hello'; $scope.msg2 = 'world'; $('.error2').html($scope.msg+'<br>'+$scope.msg2); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="error2"></div> 

Better way:

// use ng-bind-html, note: it requires angular.sanitize script

 angular.module('demo', ['ngSanitize']).controller('ctrl', function($scope) { var response = {}; response.deleted = 'some'; response.undeleted = 'text'; if (response.deleted != '') { $scope.msg = response.deleted + ' has not been deleted successfully.'; } if (response.undeleted != '') { $scope.msg2 = response.undeleted + ' has not been deleted.'; } $scope.errorText = $scope.msg + '<br>' + $scope.msg2; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-sanitize.min.js"></script> <div ng-app="demo" ng-controller="ctrl"> <div ng-bind-html="errorText"></div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM