AngularJS - “长度”方法,不计算字符串末尾的空格字符

时间:2018-04-24 09:29:19

标签: angularjs

我试图计算字符串的长度( $ scope.count = $ scope.str.lenght )。但是,当字符串末尾有一个空格时,直到空格后面有一个字符时才会计算它 示例:

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

知道为什么会这样设计?
如何计算字符串末尾的空格?

2 个答案:

答案 0 :(得分:1)

默认情况下,Angular将修剪ngModel上的尾随空格。要覆盖此行为,请添加:

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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

可能是您的角度ngModel问题不适用于Javascript。因为它在javascript中正常工作

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

  

在Angularjs,我建议@giovani回答