angular实现input输入监听

最近做用户注册登录时,需要监控用户的输入以此来给用户提示,用到了angular的$watch功能,以下是例子:
jsp:

<form class="register ng-scope" ng-app="regist_app" onsubmit="registSumbitValid()" ng-controller="regist_control">

    <div class="item">
        <input id="username" name="username" placeholder="请填写11位手机号码" class="input-item" ng-model="username" >
        <span class="warnning">{{username_error}}</span>
    </div>
</form>

这里需要添加ng-app以及ng-controller来规定一个angularApp的范围,再在input标签中添加ng-model属性,让angularjs根据这个属性来监听输入,根据输入把用户提示放到{{username_error}}中
js:

var usernameValid=false;
var registApp =angular.module('regist_app',[]);
registApp.controller('regist_control',function($scope){
    $scope.username="";
    $scope.username_error="";
    var phonePattern=/\D+/;
    /*验证号码输入*/
    $scope.$watch('username',function(newValue,oldValue){
        if(newValue!=oldValue){
            if(newValue==""){
                $scope.username_error="号码不能为空";
                usernameValid=false;
            }
            else if(phonePattern.test(newValue)){
                $scope.username_error='只能输入数字';
                usernameValid=false;
            }
            else if(newValue.length!=11){
                $scope.username_error='格式不正确,请输入11位号码';
                usernameValid=false;
            }else if(newValue.length==11){
                $scope.username_error="";
                usernameValid=true;
            }
        }
    });
}

scope. watch(参数,function),这个参数就是input的ng-model的值。function的第一个参数是新的值,第二个参数是旧的值,可以判断newValue来给用户相应的提示,结合pattern来判断用户输入是否合法。一个Controller中可以有多个 scope. watch(),这里我只贴出一个input的验证方法,其他的都差不多。
usernameValid这个值用来记录当前的input输入是否合法,用于表单提交时根据usernameValid来判断。

效果截图:
这里写图片描述

这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/caser_hdmi/article/details/77075097