[Js] Angular $timeout
博客首页 » Js Angular $timeout
发布于 01 Oct 2014 00:01
标签 blog
一个Angular $timeout的例子。重点是在使用了$timeout以后,要响应dom的$distory事件,调用$timeout.cancel(promis)。
<!doctype html> <html ng-app="Demo" ng-controller="DemoController"> <head> <meta charset="utf-8" /> <title> Don't Forget To Cancel $timeout Timers In Your $destroy Events In AngularJS </title> </head> <body> <h1> Don't Forget To Cancel $timeout Timers In Your $destroy Events In AngularJS </h1> <p> <a href="#" ng-click="toggle()">Toggle Section</a> </p> <div ng-switch="section"> <p ng-switch-when="happy" bn-directive> Oh sweet! </p> <p ng-switch-when="sad" bn-directive> Oh noes! </p> </div> <!-- Load jQuery and AngularJS. --> <script type="text/javascript" src="../../vendor/jquery/jquery-2.0.3.min.js"> </script> <script type="text/javascript" src="../../vendor/angularjs/angular-1.0.7.min.js"> </script> <script type="text/javascript"> //为我们的demo创建一个应用模块 var app = angular.module( "Demo", [] ); // -------------------------------------------------- // // -------------------------------------------------- // // 定义控制器 app.controller( "DemoController", function( $scope ) { $scope.section = "happy"; //在toggle函数中改变section的值,以此在标记中显示/隐藏不同的部分 $scope.toggle = function() { if ( $scope.section === "happy" ) { $scope.section = "sad"; } else { $scope.section = "happy"; } }; } ); // -------------------------------------------------- // // -------------------------------------------------- // //定义指令 app.directive( "bnDirective", function( $timeout ) { //将用户界面的事件绑定到$scope上 function link( $scope, element, attributes ) { //当timeout被定义时,它返回一个promise对象 var timer = $timeout( function() { console.log( "Timeout executed", Date.now() ); }, 2000 ); //将resolve/reject处理函数绑定到timer promise上以确保我们的cancel方法能正常运行 timer.then( function() { console.log( "Timer resolved!", Date.now() ); }, function() { console.log( "Timer rejected!", Date.now() ); } ); //当DOM元素从页面中被移除时,AngularJS将会在scope中触发$destory事件。这让我们可以有机会来cancel任何潜在的定时器 $scope.$on( "$destroy", function( event ) { $timeout.cancel( timer ); } ); } //返回指令的配置 return({ link: link, scope: false }); } ); </script> </body> </html>
http://www.html-js.com/article/1829
http://www.bennadel.com/blog/2548-don-t-forget-to-cancel-timeout-timers-in-your-destroy-events-in-angularjs.htm
http://www.2cto.com/kf/201311/256848.html
本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。
系列文章
文章列表
- Js Angular $timeout
这篇文章对你有帮助吗,投个票吧?
page revision: 3, last edited: 01 Oct 2014 00:10
留下你的评论