【问题标题】:HTML document preserve the new lines and spaces when using innerTextHTML 文档在使用 innerText 时保留新行和空格
【发布时间】:2018-03-21 01:46:51
【问题描述】:

我是webdevelopment 的新手。所以,在这里,我有textAngular。在这个我一个,显示html文件。现在,我只想显示文档的文本,但这应该与 .html 文件中的格式一致。所以,现在我的代码就像 -

这里的data是html文件的内容,可以说是包含html文件内容的字符串。现在,

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

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

【问题讨论】:

  • 我认为您正在寻找编译该html,尝试使用ng-html-bind="htmlOriginalDoc" from ngSanitize
  • 嘿,我试过了,但没有成功
  • 这里我在 ng-model 中使用 $rootScope.data.htmlDocument
  • pollute your $rootScope 通常是个坏主意(使用 $scope 并与服务共享值)
  • 是的,我会这样做的

标签: javascript jquery angularjs html


【解决方案1】:

基本上你需要从字符串编译它,然后用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2012-04-24
    • 2020-11-21
    • 2010-10-26
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多