Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js remove leading & trailing spaces from the input textbox

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="[email protected]" data-semver="1.9.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
    <script data-require="[email protected]" 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="";

  })
like image 210
Abdul Rehman Sayed Avatar asked Oct 19 '25 15:10

Abdul Rehman Sayed


1 Answers

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();
    }
  })
like image 61
camden_kid Avatar answered Oct 22 '25 03:10

camden_kid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!