Luk*_*rew 8 javascript angularjs
我试图通过Angularjs在网页上显示一个字符串,该字符串可能有多行.这是我得到的:
<textarea ng-model="StringValue"></textarea>
{{StringValue}}
Run Code Online (Sandbox Code Playgroud)
当您键入textarea时:
"这是
一个字符串"
你得到:
"这是一个字符串"
你如何得到它所以文本显示方式与输入相同?
Ben*_*esh 11
这是HTML的问题.不是角度的.Angular正在写出你告诉它的确切内容.
在HTML中,在<pre>标记之外,无尽的空格(返回,制表符,空格等)都被视为一个空格.这就是为什么你需要这样的东西<br/>, 如果你没有使用<pre>标签块.
因此,请尝试使用HTML,这样您就可以了解正在发生的事情:
<h3>Plain DIV</h3>
<div>
Some
text
here
</div>
<h3>Now with non-breaking spaces and line breaks</h3>
<div>
Some<br/>
text<br/>
here<br/>
</div>
<h3>Now with a PRE tag</h3>
<pre>
Some
text
here
</pre>
Run Code Online (Sandbox Code Playgroud)
您需要使用一些自定义类来设置PRE标记的样式,使其看起来像页面上的其他文本,因为大多数默认样式<pre>将使用单倍间距(固定宽度)字体,如Courier或索拉.
它要么是你要么必须用角度来编写过滤器,将空格,制表符和换行符处理成正确的标记.......这将是一种难以维持的痛苦.
所以最好的解决方案,IMO,如果你不想使用<pre>标签,那就是创建一个过滤器,为你擦除文本,并用换行符和不间断空格来对它进行远程处理.
像这样的东西
app.filter('formatText', function (){
return function(input) {
if(!input) return input;
var output = input
//replace possible line breaks.
.replace(/(\r\n|\r|\n)/g, '<br/>')
//replace tabs
.replace(/\t/g, ' ')
//replace spaces.
.replace(/ /g, ' ');
return output;
};
});
Run Code Online (Sandbox Code Playgroud)
然后使用它你会做这样的事情:
<span ng-bind-html="foo | formatText"></span>
Run Code Online (Sandbox Code Playgroud)
angular-sanitize.js在脚本引用中包含该文件.'ngSanitize'在模块声明中要求:var app = angular.module('myApp', ['ngSanitize']);
Run Code Online (Sandbox Code Playgroud)
..这是你可以使用ng-bind-html或ng-bind-html-unsafe指令.
vp_*_*rth 10
小心ng-bind-html- 很容易得到XSS注射.
如果您只想显示新行,在页面中没有XSS,您
可以使用简单的css-rule white-space: pre::
<span style="white-space: pre">{{multilinetext}}</span>
Run Code Online (Sandbox Code Playgroud)
当然,你可以为此制作css级:
<style>.pre {white-space: pre}</style>
<span class="pre">{{multilinetext}}</span>
Run Code Online (Sandbox Code Playgroud)
此外,此方法使所有空格可见:前导空格,多个空格选项卡等.
正如其他答案所提到的,您可以使用过滤器来实现它.
让我为你实现它:
<textarea ng-model="StringValue"></textarea>
<div ng-bind-html-unsafe="StringValue | breakFilter"></div>
angular.module('myApp', []).filter('breakFilter', function () {
return function (text) {
if (text !== undefined) return text.replace(/\n/g, '<br />');
};
});
Run Code Online (Sandbox Code Playgroud)