angular實現(xiàn)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根據(jù)這個屬性來監(jiān)聽輸入,根據(jù)輸入把用戶提示放到{{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='只能輸入數(shù)字'; 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(參數(shù),function),這個參數(shù)就是input的ng-model的值。function的第一個參數(shù)是新的值,第二個參數(shù)是舊的值,可以判斷newValue來給用戶相應(yīng)的提示,結(jié)合pattern來判斷用戶輸入是否合法。一個Controller中可以有多個scope.scope.watch(),這里我只貼出一個input的驗證方法,其他的都差不多。
usernameValid這個值用來記錄當前的input輸入是否合法,用于表單提交時根據(jù)usernameValid來判斷。
效果截圖:
以上這篇angular實現(xiàn)input輸入監(jiān)聽的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
深入淺析AngularJS中的一次性數(shù)據(jù)綁定 (bindonce)
這篇文章主要介紹了AngularJS中的一次性數(shù)據(jù)綁定 (bindonce)知識,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-05-05AngularJS基于ui-route實現(xiàn)深層路由的方法【路由嵌套】
這篇文章主要介紹了AngularJS基于ui-route實現(xiàn)深層路由的方法,涉及AngularJS路由嵌套操作相關(guān)實現(xiàn)步驟與技巧,需要的朋友可以參考下2016-12-12