加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

[笔记]$watch监听input,输入空格不触发回调问题

发布时间:2020-12-15 01:18:53 所属栏目:C语言 来源:网络整理
导读:利用$watch监听input中输入的值,当输入空格时,回调函数没有触发,导致无法限制空格的输入问题。 一、现象 body ng-controller="exerciseController" input type="text" ng-model="txt" /body angular.module('app',[]).controller('exerciseController',fu

利用$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">

这样的话,即使输入空格也是有响应的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读