d_unknown d_unknown - 5 months ago 33
AngularJS Question

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?

Answer

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>

Comments