如何使用换行符显示文本

时间:2017-03-23 10:14:33

标签: html angularjs

enter image description here

我需要用换行符显示文本,这是脚本

<script>
    var app = angular.module('MyApp', []);
    app.controller('Ctrl', function ($scope) {
        console.log('Controller is executed');
        $scope.btnClick = function () {
            console.log($scope.desc);
        }
        $scope.ShowData = function () {
            $scope.text = $scope.desc;
        }
    });
</script>

这是html代码

<body ng-controller="Ctrl">
<form>
    <textarea ng-model="desc" cols="105" rows="15"></textarea>
    <button ng-click="btnClick()">Submit</button>
    <button ng-click="ShowData()">Show</button>
</form>
<div ng-bind="text"></div>

6 个答案:

答案 0 :(得分:10)

尝试在<pre></pre>标记内而不是<div>内呈现文字。 或者在你的div上使用style="white-space:pre-wrap;"

答案 1 :(得分:5)

使用正确的CSS。 pre标记的默认样式会保留换行符:

<pre>{{text}}</pre>

或者您可以使用CSS(white-space):

div {
    white-space: pre; /* or pre-wrap or pre-line */
    /* https://developer.mozilla.org/en-US/docs/Web/CSS/white-space */
}

答案 2 :(得分:2)

在显示文字的位置添加pre代码 <pre></pre>

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
<body ng-app="">

<p>Write something with breaks and check:</p>

<textarea ng-model="myTextarea"></textarea>

<p>The content of the textarea is;</p>
<pre><span>{{myTextarea}}</span></pre>

</body>
</html>

请运行以上代码

Here is a working DEMO

答案 3 :(得分:0)

使用:

<script>
    var app = angular.module('MyApp', []);
    app.controller('Ctrl', function ($scope) {
        console.log('Controller is executed');
        $scope.btnClick = function () {
            console.log($scope.desc);
        }
        $scope.ShowData = function () {
            $scope.text = $scope.desc.replace(/\r?\n/g, '<br />');
        }
    });
</script>

换行符(\ n \ r?)与HTML&lt;不同br /&gt;标签

答案 4 :(得分:0)

在CSS上添加样式

  <body ng-controller="Ctrl">
    <form>
        <textarea ng-model="desc" cols="105" rows="15"></textarea>
        <button ng-click="btnClick()">Submit</button>
        <button ng-click="ShowData()">Show</button>
    </form>
    <div ng-bind="text" class="line-break"></div>

<style>
    .line-break {
    width: 90px; //Give some width accoring you
    overflow-wrap: break-word;
    }
 </style>

答案 5 :(得分:0)

只需将其添加到您的样式中,这对我有用

white-space: pre-wrap

HTML

   <p class="text-style">{{product?.description}}</p>

CSS

.text-style{
    white-space: pre-wrap
}

<textarea>中的此文本可以在那里显示,带有空格和线制动器