【问题标题】:Why is this Angular JS filter removing spaces?为什么这个 Angular JS 过滤器会删除空格?
【发布时间】:2014-05-30 23:02:26
【问题描述】:

我正在制作一个小型应用程序来学习 Angular,并为文本处理制作了一个自定义过滤器。一切正常,除了在我的输出文本有多个空格的情况下,这些会自动减少为一个空格,这是我不想要的。问题不在我定义的函数中,因为我正在记录输出,这没有问题。

HTML:

<textarea name="textarea" rows="10" cols="50" ng-model="encodeText" placeholder="Type or paste in a message to encode." ></textarea>
<p>Filtered input: {{ encodeText | encode }}</p>

JS:

(function(){
  var app = angular.module('myApp', []);
  app.filter("encode", function() {
    return function(input) {
      if (input) {
        //text processing
        console.log(output);
        return output;
      }
    };
 });

这是一个摩尔斯电码练习。所以控制台日志输出为:

.- -... -.-.   -.. . ..-. 

有两个空格。在我看到的页面上:

Filtered input: .- -... -.-. -.. . ..-.

我从谷歌上看到的唯一建议是在 textarea 上使用 ng-trim="false",但没有任何效果。似乎修剪发生在过滤器本身内。是什么原因造成的,我该如何禁用它? Code repo

【问题讨论】:

    标签: javascript angularjs angular-ngmodel


    【解决方案1】:

    默认情况下,HTML 不保留多个空格(将它们折叠成 1 个空格)。给&lt;p&gt;标签添加样式到preserve whitespace...

    <p style="white-space: pre">Filtered input: {{ encodeText | encode }}</p>
    

    【讨论】:

    • 谢谢。这个作品似乎有一些小的跨浏览器问题。
    【解决方案2】:

    p格式化您的输出。 试试:

    <pre>{ encodeText | encode }</pre>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 2019-09-12
      • 1970-01-01
      • 2021-04-13
      • 2015-04-25
      • 1970-01-01
      • 2015-02-20
      相关资源
      最近更新 更多