Pregunta

I want to bind an input to some other part of the page and replace all whitespaces the user has entered with some other characters, like asterisks for example.

My (simplified) HTML code looks like this:

<div ng-app>
    <div ng-controller="MyCtrl">
        Output: "{{input}}"<br />
        <input type="text" ng-model="rawInput" ng-change="onInputChanged()" />
    </div>
</div>

The relevant controller is quite simple, too:

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.input = '';
    $scope.rawInput = '';
    $scope.onInputChanged = function() {
        $scope.input= $scope.rawInput .replace(/\s/g, '*');
    };
};

The result is not as expected. When entering 'Hello ' into the textbox the resulting output is "Hello" with the trailing whitespace being removed. The same goes for multiple whitespaces at the end of the input.

When adding a non-whitespace character to the input, like 'Hello W', the whitespaces are being properly replaced and displayed: "Hello*World".

So here's my question: How can I bind to the value of the textbox preserving all whitespaces a user has entered?

I created JSFiddle demonstrating the issue.

¿Fue útil?

Solución

Set ng-trim="false" in your input.

From angular documentation

If set to false Angular will not automatically trim the input.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top