prime
prime

Reputation: 15574

Leading spaces are not displayed in AngularJS

I tried the following angularJS code sample.

<div ng-app="">

  <p>Input something in the input box:</p>
  <p>Name : <input  type="text" ng-model="name" placeholder="Enter name here"></p>
  <h1>Hello {{name}}</h1>

</div>

This works fine but when I enter a string with leading spaces it will simply trim them out. How can I use this to display a string with leading spaces. (btw I don't want to display string with only spaces)

Upvotes: 2

Views: 2118

Answers (2)

Andy Gaskell
Andy Gaskell

Reputation: 31761

Add ng-trim="false" to your input. Confirm that ng-trim worked by changing to a pre wrapped with quotes.

<input type="text" ng-model="name" ng-trim="false" placeholder="Enter name here">

<pre>Hello '{{name}}'</pre>

Here's the code to ignore fully blank names:

<pre>Hello '<span ng-show="name.trim().length > 0">{{name}}</span>'</pre>

Plunker

Upvotes: 3

gaiazov
gaiazov

Reputation: 1960

It is not angular that is trimming your spaces, it is HTML not rendering multiple spaces.

Change your code to the following and you will see your spaces:

<div ng-app="">

<p>Input something in the input box:</p>
<p>Name : <input  ng-model="name" placeholder="Enter name here"></p>
<pre>Hello {{name}}</pre>

</div>

Upvotes: 0

Related Questions