angular實現input輸入監(jiān)聽的示例
最近做用戶注冊登錄時,需要監(jiān)控用戶的輸入以此來給用戶提示,用到了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="請?zhí)顚?1位手機號碼" class="input-item" ng-model="username" >
<span class="warnning">{{username_error}}</span>
</div>
</form>
這里需要添加ng-app以及ng-controller來規(guī)定一個angularApp的范圍,再在input標簽中添加ng-model屬性,讓angularjs根據這個屬性來監(jiān)聽輸入,根據輸入把用戶提示放到{{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輸入監(jiān)聽的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
快速解決angularJS中用post方法時后臺拿不到值的問題
今天小編就為大家分享一篇快速解決angularJS中用post方法時后臺拿不到值的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
對angularJs中ng-style動態(tài)改變樣式的實例講解
今天小編就為大家分享一篇對angularJs中ng-style動態(tài)改變樣式的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
angular4中*ngFor不能對返回來的對象進行循環(huán)的解決方法
今天小編就為大家分享一篇angular4中*ngFor不能對返回來的對象進行循環(huán)的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
AngularJS入門教程之與服務器(Ajax)交互操作示例【附完整demo源碼下載】
這篇文章主要介紹了AngularJS與服務器Ajax交互操作的方法,可實現post傳輸數據的功能,并附帶完整的demo源碼供讀者下載參考,源碼中還包含了前面章節(jié)的示例文件,需要的朋友可以參考下2016-11-11
詳解基于Angular4+ server render(服務端渲染)開發(fā)教程
本篇文章主要介紹了詳解基于Angular4+ server render(服務端渲染)開發(fā)教程 ,具有一定的參考價值,有興趣的可以了解一下2017-08-08

