2015-01-02 59 views
1

我正在使用angular。 我有一個輸入框輸入6位數後,我必須點擊按鈕。如何在輸入框中輸入6位數字後調用函數angularjs

<input type="tel" ng-model="loginData.otp" id="otp1" placeholder="OTP" > 
     </label> 
     <label class="item"> 
     <button class="button button-block button-positive" id="otplogin" type="submit">Login</button> 

    </label> 

我有一個輸入框後輸入6位數字,我需要點擊按鈕。 輸入6位數後我怎樣才能調用函數?我不需要點擊按鈕?

回答

0

您也可以使用$ scope。$ watch來觀察輸入的長度。

function TodoCtrl($scope){ 
    $scope.loginData = { otp: '' }; 

    $scope.$watch('loginData.otp.length', function(newValue, oldValue){ 
     if(newValue == 6){ 
      alert('Process to next level'); 
      // put your function here 
     } 
    }); 
} 

http://jsfiddle.net/Zing87/po9rxsLs/1/

看看我的答案
1

您可以使用ng-change屬性,如ng-change="inputChanged()"。在你的控制器,你有

$scope.inputChanged = function() { 
    // Check value of $scope.loginData.otp here, example: 
    if(!$scope.loginData.otp || $scope.loginData.otp.length < 5) { 
     return; 
    } 
    // then you continue with your processing 
}; 

檢查更多的文檔:

https://docs.angularjs.org/api/ng/directive/ngChange

更新:

目前公認的答案使用$watch。你應該儘量減少在控制器中使用$watch(只要有可能,只需在指令中,an example of why)。

在這個問題中,您說您對由於用戶輸入而產生的價值變化感興趣,所以我認爲使用視圖的change指令是有意義的,因爲它是用戶更改事件。

相關問題