我在學習Angular JS 1時正在進行一些測試。我有一些文本區域在用戶進入和退出時通過Angular函數顯示一些文本。 enter函數等待3秒鐘,退出函數等待5秒鐘。這工作到目前爲止。在AngularJS中停止計時函數1
該任務的下一部分是如果用戶不等待超時數量,則取消將文本綁定到文本區域的功能。我很困惑,但我認爲我需要使用承諾。
var myApp = angular.module('myApp', []);
function checkTimeout() {
console.log("Timeout is working...");
}
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}])
myApp.controller("MyCtrl", function($scope, $timeout){
$timeout(checkTimeout, 3000);
$scope.data = [{
"id": 1,
"act": ""
}, {
"id": 2,
"act": ""
}, {
"id": 3,
"act": ""
}, {
"id": 4,
"act": ""
}, {
"id": 5,
"act": ""
}, {
"id": 6,
"act": ""
}, {
"id": 7,
"act": ""
}, {
"id": 8,
"act": ""
}, {
"id": 9,
"act": ""
}];
$scope.enter1 = function(num) {
$timeout (function(){num.act = " - enter";}, 3000);
}
$scope.exit1 = function(num) {
$timeout (function(){num.act = " - exit";}, 5000);
}
})
HTML:
<body ng-app="myApp">
<div ng-controller="MyCtrl" style="width:100%;margin:10px;">
<p>How can I stop the functions enter1 and exit1 from binding text to the textarea if the user does not wait the 3 seconds (enter1) and 5 seconds (exit1) for them to execute?</p>
<div style="float:right; width:49%;">
<div ng-repeat="num in data" style="margin:3px;">
<textarea ng-focus="enter1(num)" ng-blur="exit1(num)">{{ num.id }}{{ num.act }}</textarea>
</div>
</div>
</div>
</body>
這裏的小提琴:https://jsfiddle.net/mediaguru/q3qt5frk/
感謝Dominic的迴應。所以在你的例子中,如果它發生在3000ms內,我將如何與$ timeout.cancel模糊?希望這並不太清楚。 – mediaguru
基本上,每當你啓動一個計時器,就把它存儲在一個變量中。如果您需要提前結束計時器,請在變量上調用$ timeout.cancel。否則,讓它運行並忽略它。我會添加更多的上下文,但我不確定我瞭解您的問題。 –
讓我們只是採取焦點功能。用戶在該字段中標籤或點擊。如果用戶在現場停留3秒或更長時間,則字段中會顯示「enter」字樣。如果用戶在3秒前離開該字段,則不會出現Enter字樣。 – mediaguru