HTML 文档在使用 innerText 时保留新行和空格



我是webdevelopment新手。所以,在这里,我有textAngular.在此我a中,显示html文档。现在,我只想显示文档的文本,但这应该与.html文件中的格式相同。所以,现在我的代码是这样的——

这里的数据是HTML文件内容,你可以说它是一个包含HTML文件内容的字符串。现在

$scope.htmlOriginalDoc = parser.parseFromString(data, 'text/html');
$rootScope.data.htmlDocument = $scope.htmlOriginalDoc.body.innerText;
所以,当我

得到这个的时候,我正在获取该文件的所有数据,但是当我看到它就像一个文本文档时,它没有任何新行,我的意思是它没有保留新行或空格。那么,我怎样才能做到这一点呢?

基本上你需要从字符串编译它,然后用ngSanitize绑定它。保留带有<pre>标记的空格换行。

var app = angular.module('myApp', ['ngSanitize']);
app.controller('myCtrl', function($scope, $sce) {
  $scope.html = "<div style="color:red;font-size:24px;">    T   e  s t    </div>"; // string
  $scope.html = $sce.trustAsHtml($scope.html);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-sanitize.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div style="white-space: pre;"> <!-- instead of <pre> -->
    <div ng-bind-html="html"></div>
  </div>
</div>

最新更新