$timeout是什麼?
timeout 顧名思義是和時間有關,用來倒數、計時的一種方法。
而$timeout則是應用於angular的指令
本日參考範例:
http://jsbin.com/eyaPAtU/1/edit
http://jsbin.com/EmijUBi/1/edit
http://jsbin.com/EYiyUGe/2/edit
$timeout怎麼用?
說明$timeout之前,先介紹window 物件的 setInterval() 方法
可以參考w3schools文件,
http://www.w3schools.com/jsref/met_win_setinterval.asp
第一個範例是:
使用angular,結合window 物件的 setInterval() 方法
啓動timeout
var timer = setInterval(function(){
$scope.countDown--;
$scope.$apply();
console.log($scope.countDown);
}, 1000);
取消timeout
$scope.stop = function(){
window.clearInterval(timer);
};
範例來源參考:
http://stackoverflow.com/questions/12050268/angularjs-make-a-simple-countdown
改寫Demo:
http://jsbin.com/eyaPAtU/1/edit
第二個範例是:
運用angular的$timeout指令
html:
<body ng-controller="Ctrl">
js:
function Ctrl($scope,$timeout) { }
透過$timeout觸發timeout
$scope.onTimeout = function(){
$scope.counter++;
mytimeout = $timeout($scope.onTimeout,1000);
};
var mytimeout = $timeout($scope.onTimeout,1000);
再使用$timeout.cancel執行停止timeout的事件,
$scope.stop = function(){
$timeout.cancel(mytimeout);
};
改寫Demo:
http://jsbin.com/EmijUBi/1/edit
第三個範例是:
運用angular的$timeout指令,倒數後執行按鈕無法點選的行為案例
http://jsbin.com/EYiyUGe/2/edit
參考資料:
官方說明文件: http://docs.angularjs.org/api/ng.$timeout
官方複雜的demo: http://jsfiddle.net/api/post/library/pure/
第2個範例來源: http://jsfiddle.net/ganarajpr/LQGE2/
第3個範例來源: http://stackoverflow.com/questions/16069309/how-to-change-value-after-delay-by-using-angularjs
進階應用-How to put a delay on AngularJS instant search?:
http://stackoverflow.com/questions/15304562/how-to-put-a-delay-on-angularjs-instant-search
進階應用-directive:
http://stackoverflow.com/questions/16824157/angularjs-directive-how-do-i-hide-the-alert-using-timeout
進階應用-動態變換字串
http://jsfiddle.net/b8KLQ/3/