您的位置:首页 > Web前端 > AngularJS

angular实现input输入监听的示例

2018-08-31 10:57 567 查看

最近做用户注册登录时,需要监控用户的输入以此来给用户提示,用到了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.scope.watch(参数,function),这个参数就是input的ng-model的值。function的第一个参数是新的值,第二个参数是旧的值,可以判断newValue来给用户相应的提示,结合pattern来判断用户输入是否合法。一个Controller中可以有多个scope.scope.watch(),这里我只贴出一个input的验证方法,其他的都差不多。

usernameValid这个值用来记录当前的input输入是否合法,用于表单提交时根据usernameValid来判断。

效果截图:

以上这篇angular实现input输入监听的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angular input 监听