Brian Davis
Brian Davis

Reputation: 357

Why is this Angular JS filter removing spaces?

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

Upvotes: 1

Views: 2842

Answers (2)

Paul Rad
Paul Rad

Reputation: 4882

The pformat your output. Try:

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

Upvotes: 2

Anthony Chu
Anthony Chu

Reputation: 37530

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>

Upvotes: 7

Related Questions