[英]Angular one: javascript timeout function
我正在嘗試基於輸入值調用函數。 該方案將:如果10秒鍾內沒有人在該輸入中添加任何內容(因此該值將為null),請禁用該輸入。 我想使用ng-change或類似的角度方法來代替任何“鍵盤鍵”條件。
現在,首先想到的是單擊按鈕時將計時器設置為0並計數為10。
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 10;
$scope.inpValue = '';
function myFunction() {
setTimeout(function() {
if ($scope.inpValue.length === 0 && $scope.count >= 10) {
alert("Execute function when if is true");
}
}, 1000);
};
myFunction();
}]);
盡管問題陳述不明確,但這可能是您所需要的。
input
框中輸入任何值,它將在10秒鍾內禁用。 resets
為默認值並重新運行。 Close on 10
按鈕還可以重置計時器,但是一旦單擊按鈕,該按鈕將被disabled
。 僅在input
框的值更改時enabled
。 angular.module('myApp', []).controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) { $scope.count = 1; $scope.inpValue = ""; $scope.disableInput = false; $scope.disableBtn = false; $scope.checkToDisable = function() { console.log($scope.count); $scope.customTimeout = $timeout(function() { if ($scope.inpValue.length === 0 && $scope.count == 10) { $scope.count = 0; $scope.disableInput = true; $scope.disableBtn = true; $timeout.cancel($scope.customTimeout); } else { $scope.count++; $scope.checkToDisable(); if ($scope.count > 10) { $timeout.cancel($scope.customTimeout); } } }, 1000); }; $scope.resetTimer = function() { $scope.count = 1; $timeout.cancel($scope.customTimeout); $scope.checkToDisable(); }; $scope.checkToDisable(); }]);
button { border: none; padding: 5px 2px; border-radius: 4px; box-shadow: inset 1px 1px 4px red; } button:active { background: orange; border: none; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body ng-app="myApp"> <div ng-controller="myCtrl"> <input type='text' ng-model="inpValue" ng-change="resetTimer(); disableBtn = false;" ng-disabled="disableInput" /> <button ng-click="resetTimer(); disableBtn = true;" ng-disabled="disableBtn">Close when it reaches 10</button> </div> </body>
這是一種可能對您繼續有用的方法:
HTML:
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type='text' ng-model="inpValue" placeholder='Something here' ng-change="myFunction()" />
<button>Close when it reaches 10
</button>
</div>
</body>
JavaScript的
angular.module('myApp', []).controller('myCtrl', ['$scope', function($scope)
{
$scope.count = 10;
$scope.inpValue = '';
function myFunction() {
setTimeout(function() {
if ($scope.inpValue.length === 0 && $scope.count >= 10) {
alert("Execute function when if is true");
}
}, 10000);
};
myFunction();
}]);
完整樣本: https : //jsfiddle.net/Lv2Lb1a6/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.