Why is this Angular JS filter removing spaces?

谁说胖子不能爱 提交于 2020-01-03 03:13:10

问题


I'm making a tiny app to learn Angular, and have made a custom filter for text processing. Everything is working fine, except that in cases when my output text has multiple spaces, these get automatically reduced to a single space, which I don't want. The issue is not in the function I've defined, because I'm logging the output, which does not have the problem.

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;
      }
    };
 });

It is a Morse Code exercise. So console log output is:

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

With two spaces. On the page I see:

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

The only suggestion I'm seeing from Googling is using ng-trim="false" on the textarea, which has no effect. It seems the trimming is happening within the filter itself. What is causing this and how do I disable it? Code repo


回答1:


The pformat your output. Try:

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



回答2:


By default, HTML doesn't preserve multiple whitespaces (collapses them into 1 space). Add a style to the <p> tag to preserve whitespace...

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


来源:https://stackoverflow.com/questions/23964573/why-is-this-angular-js-filter-removing-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!