字符串中的换行符js

时间:2016-06-10 07:43:56

标签: javascript html angularjs

如果删除表格中的行,我会收到类似通知的内容。我实际上使用的是angularjs,所以它在ngcontroller函数中。我的html中有一个标签,它会显示一条在ngcontroller中初始化的消息。像这样,

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); 

我希望用新行分隔两条消息,但没有任何反应。如果我将\n替换为<br>,它实际上会打印出<br>。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:2)

简短的asnwer:

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

演示:

&#13;
&#13;
// temporary duck
$scope = {};
$scope.msg = 'hello';
$scope.msg2 = 'world';

$('.error2').html($scope.msg+'<br>'+$scope.msg2); 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="error2"></div>
&#13;
&#13;
&#13;

更好的方式:

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

&#13;
&#13;
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;
});
&#13;
<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>
&#13;
&#13;
&#13;