[英]Loop in directive and ng-change Angular JS
我有下一個問題,我在Angular JS中創建了一個指令來檢查輸入是否為數字,如果不是數字,則需要設置正確的值。 這是我的指令代碼:
app.directive('numberValidate', function(){
return {
require: 'ngModel',
link: function($scope, element, attr, modelCtrl){
modelCtrl.$parsers.push(function (inputValue){
var transformedInput = parseInt(inputValue);
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
另外,當用戶停止鍵入發送請求時,我需要收聽。 為了在停止時進行監聽,我在該字段中添加了ng-model-options="{debounce: 750}"
,如下面的代碼所示:
<input type="text" ng-change="sendChecker()" ng-model="identification" ng-model-options="{debounce: 750}" number-validate>
sendChecker
函數將我的請求激發到服務器,當我寫一個類似12345
的數字或鍵入帶有字符12345a
的數字時,一切正常,這將轉換為數字並在輸入中設置,問題是當我寫a
由此創建的字母時一個循環。 如何避免這種情況?
任何建議將不勝感激。
為什么不使用ng-pattern
來驗證輸入?
<input type="text" ng-pattern=/^[0-9]+$/ ng-model="identification" ng-model-options="{debounce: 750}">
或者您可以使用輸入類型number
<input type="number" ng-model="identification" ng-model-options="{debounce: 750}">
然后,您不必自己驗證某些內容?
編輯:
在以下示例中,僅當用戶插入有效值時才調用sendChecker()
<form name="myform">
<input type="number" name="myinput" ng-changed="myform.myinput.$valid ? sendChecker(identification) : " ng-model="identification" ng-model-options="{debounce: 750}">
</form>
因為parseInt('12345a') == 12345
您進入了循環。 因此,您需要從字符串中過濾掉非數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.