3

I was trying to count the length of a string($scope.count = $scope.str.lenght). But, when there is a space at the end of the string its not being counted until there is a character after the space.
Example:

"Hello " = 5,  
"Hello u" = 7  

Any idea why is it designed in this way?
How can I count the space at the end of the string?

4
  • post your code. what you have tried Commented Apr 24, 2018 at 9:33
  • In console, "Hello ".length get true output! insert some code please. Commented Apr 24, 2018 at 9:39
  • @Saeed.At Pure javascript works fine, it's Angular that seems to trim the ngModel value. Commented Apr 24, 2018 at 9:43
  • Try ng-trim="false" Commented Apr 24, 2018 at 9:45

2 Answers 2

2

By default Angular will trim the trailing spaces on ngModel. To override this behaviour add:

ng-trim="false"

more info

(function() {
	'use strict';
  
  angular.module('myApp', []);
  
  angular.module('myApp').controller('MyController', MyController);
  
  MyController.$inject = [];
  function MyController() {
    var main = this;
    main.someText = 'abcde';

  }
  
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="MyController as main">
    <input type="text" ng-model="main.someText" ng-trim="false">
    {{main.someText.length}}
  </div>
</body>

Sign up to request clarification or add additional context in comments.

Comments

0

May be your having the problem with angular ngModel not for the Javascript. Because it is working correct in javascript

console.log("hello ".length)
console.log("hello u".length)

In Angularjs I would suggest @giovani answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.