Angular js remove leading & trailing spaces from the input textbox

angularjs, javascript

Solution

Would this work? - Plunker

`ng-blur` doesn't work with your Plunker because the version of AngularJS you are loading (1.0.7) is quite old. I replaced it with the latest version (1.5.6). I also use `ng-trim="false"` to get the correct text input by the user.

Markup

<body ng-controller="MyCtrl">
    <input type="text" ng-model="modelVal" ng-change="change()" ng-blur="blur()" ng-trim="false">
    <br>
    model value is "{{newModelVal}}"
</body>

JS

angular.module('app', [])
  .controller('MyCtrl', function($scope) {
    $scope.modelVal="";
    $scope.change = function () {
      $scope.newModelVal = $scope.modelVal;
    }
    $scope.blur = function () {
      $scope.modelVal = $scope.newModelVal.trim();
    }
  })

Problem

See this Plunkr : http://plnkr.co/edit/YAQooPn0UERDI5UEoQ23?p=preview Type text as "_______what___ever_____" (without quotes & _ represents spaces.) Angular is removing spaces (from front & back & not in between) from the model (which is my desired behavior), but my textbox is keeping the spaces. how can I remove the spaces from the textbox also ? i.e. I want the textbox also to reflect the value in model. Edit: Better explanation of my needs. For Eg: If I typed "___What_Ever____" ( without quote & _ is space), 1) my textbox will show me same what i have typed i.e. "___What_Ever____" 2) while my model will show me "What Ever". I want my textbox's value also to be as "What Ever". HTML : ``` <!DOCTYPE html> <html ng-app="app"> <head> <link rel="stylesheet" href="style.css" /> <script data-require="jquery@1.9.0" data-semver="1.9.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.js"></script> <script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script> <script src="script.js"></script> </head> <body ng-controller="MyCtrl"> <input type="text" ng-model="modelVal"> <br> model value is "{{modelVal}}" </body> </html> ``` JS : ``` angular.module('app', []) .controller('MyCtrl', function($scope) { $scope.modelVal=""; }) ```

Original source