我想将输入绑定(bind)到页面的其他部分,并将用户输入的所有空格替换为其他字符,例如星号。
我的(简化的)HTML 代码如下所示:
<div ng-app>
<div ng-controller="MyCtrl">
Output: "{{input}}"<br />
<input type="text" ng-model="rawInput" ng-change="onInputChanged()" />
</div>
</div>
相关的 Controller 也很简单:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.input = '';
$scope.rawInput = '';
$scope.onInputChanged = function() {
$scope.input= $scope.rawInput .replace(/\s/g, '*');
};
};
结果并不如预期。当在文本框中输入 'Hello '
时,结果输出为 "Hello"
并删除了尾随空格。对于输入末尾的多个空格也是如此。
在输入中添加非空白字符(例如 'Hello W'
)时,空白会被正确替换并显示:"Hello*World"
。
所以这是我的问题:如何绑定(bind)到保留用户输入的所有空格的文本框的值?
我创建了JSFiddle演示该问题。
最佳答案
在输入中设置ng-trim="false"
。
If set to false Angular will not automatically trim the input.
关于angularjs - 如何强制 angular.js 接受绑定(bind)中的尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23633434/