利用$watch监听input中输入的值,当输入空格时,回调函数没有触发,导致无法限制空格的输入问题。
一、现象
<body ng-controller="exerciseController"> <input type="text" ng-model="txt" > </body>
angular.module('app',[]).controller('exerciseController',function($scope){ $scope.txt = ''; $scope.$watch('txt',function(newValue,oldValue) { console.log('newValue',newValue); console.log('oldValue',oldValue); }); });
给input双向绑定了一个txt的变量,然后监听他的变化。
输入空格,控制台并没有打印,输入字符却有。在两个字符之间输入空格,也是有打印的,可以判定,触发回调时进行对比的值是会经过trim(去前后空格)方法的。
二、ng-trim
因此,我们不需要angular为我们进行trim操作,所以我们只要在input中添加属性 ng-trim=”false”。
<input type="text" ng-model="txt" ng-trim="false">
这样的话,即使输入空格也是有响应的。