@@ -31,6 +31,94 @@ function $TimeoutProvider() {
3131 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
3232 * @returns {Promise } Promise that will be resolved when the timeout is reached. The value this
3333 * promise will be resolved with is the return value of the `fn` function.
34+ *
35+ * @example
36+ <doc:example module="time">
37+ <doc:source>
38+ <script>
39+ function Ctrl2($scope,$timeout) {
40+ $scope.format = 'M/d/yy h:mm:ss a';
41+ $scope.blood_1 = 100;
42+ $scope.blood_2 = 120;
43+
44+ var stop;
45+ $scope.fight = function() {
46+ stop = $timeout(function() {
47+ if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
48+ $scope.blood_1 = $scope.blood_1 - 3;
49+ $scope.blood_2 = $scope.blood_2 - 4;
50+ $scope.fight();
51+ } else {
52+ $timeout.cancel(stop);
53+ }
54+ }, 100);
55+ };
56+
57+ $scope.stopFight = function() {
58+ $timeout.cancel(stop);
59+ };
60+
61+ $scope.resetFight = function() {
62+ $scope.blood_1 = 100;
63+ $scope.blood_2 = 120;
64+ }
65+ }
66+
67+ angular.module('time', [])
68+ // Register the 'myCurrentTime' directive factory method.
69+ // We inject $timeout and dateFilter service since the factory method is DI.
70+ .directive('myCurrentTime', function($timeout, dateFilter) {
71+ // return the directive link function. (compile function not needed)
72+ return function(scope, element, attrs) {
73+ var format, // date format
74+ timeoutId; // timeoutId, so that we can cancel the time updates
75+
76+ // used to update the UI
77+ function updateTime() {
78+ element.text(dateFilter(new Date(), format));
79+ }
80+
81+ // watch the expression, and update the UI on change.
82+ scope.$watch(attrs.myCurrentTime, function(value) {
83+ format = value;
84+ updateTime();
85+ });
86+
87+ // schedule update in one second
88+ function updateLater() {
89+ // save the timeoutId for canceling
90+ timeoutId = $timeout(function() {
91+ updateTime(); // update DOM
92+ updateLater(); // schedule another update
93+ }, 1000);
94+ }
95+
96+ // listen on DOM destroy (removal) event, and cancel the next UI update
97+ // to prevent updating time ofter the DOM element was removed.
98+ element.bind('$destroy', function() {
99+ $timeout.cancel(timeoutId);
100+ });
101+
102+ updateLater(); // kick off the UI update process.
103+ }
104+ });
105+ </script>
106+
107+ <div>
108+ <div ng-controller="Ctrl2">
109+ Date format: <input ng-model="format"> <hr/>
110+ Current time is: <span my-current-time="format"></span>
111+ <hr/>
112+ Blood 1 : <font color='red'>{{blood_1}}</font>
113+ Blood 2 : <font color='red'>{{blood_2}}</font>
114+ <button type="button" data-ng-click="fight()">Fight</button>
115+ <button type="button" data-ng-click="stopFight()">StopFight</button>
116+ <button type="button" data-ng-click="resetFight()">resetFight</button>
117+ </div>
118+ </div>
119+
120+ </doc:source>
121+ </doc:example>
34122 */
35123 function timeout ( fn , delay , invokeApply ) {
36124 var deferred = $q . defer ( ) ,
0 commit comments