Angular implements input input monitoring

When doing user registration and login recently, it is necessary to monitor the user's input to prompt the user. The $watch function of angular is used. The following is an example:
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>

Here you need to add ng-app and ng-controller to specify the scope of an angularApp, and then add the ng-model attribute to the input tag, let angularjs monitor the input according to this attribute, and put the user prompt into {{username_error}} according to the input
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(parameter, function), this parameter is the value of the input ng-model. The first parameter of the function is the new value, and the second parameter is the old value. You can judge the newValue to give the user corresponding prompts, and combine the pattern to judge whether the user input is legal. A Controller can have multiple scope. watch(), here I only post an input validation method, the others are similar.
The value of usernameValid is used to record whether the current input is legal or not, and is used to judge according to usernameValid when the form is submitted.

Screenshot of the effect:
write picture description here

write picture description here

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325636396&siteId=291194637