How to execute a sequence of events in Angular using $timeout

最后都变了- 提交于 2020-01-11 13:01:11

问题


I have a div in my view, I want to execute a function on ng-click() which turns the background for the div to 'color a' for 30 seconds if there's no action taken then for 60 seconds then change to 'color b' and if no action is taken beyond 120 seconds just hide the div.(this can be done via adding/removing classes as well )

In essence I'm looking to execute a sequence of $timeouts in angular where one timeout leads into another.

Any help on that would be hugely appreciated. Thanks.


回答1:


I would approach it by using a variable in the scope to hold the state, and chaining $timeouts to move between the states. So on the element that will be clicked:

<span ng-click="startChange()">Click me to start</span>

and in the controller:

$scope.state = 'a';
$scope.startChange = function() {
  $scope.state = 'b';
  return $timeout(angular.noop, 30 * 1000).then(function() {
    $scope.state = 'c';
    return $timeout(angular.noop, 60 * 1000);
  }).then(function() {
    $scope.state = 'd';
    return $timeout(angular.noop, 120 * 1000);
  }).then(function() {
    $scope.state = 'e'
  });
}

The angular.noop is just a function that does nothing. It's a slightly personal preference, but I find it a bit easier to see the flow of activity where the callback passed to $timeout does nothing, and all action on the scope are always in the then success callback of the promise.

In the template for the background div:

<div class="background-state-{{state}}">....</div>

and then in CSS set the colours:

.background-state-a {background-color: red}
.background-state-b {background-color: green}
.background-state-c {background-color: blue}
...

However, I'm not sure what else you have in the controller or your exact use-case. You might want to separate some logic out into a directive, as it might be mixing business logic with view logic.



来源:https://stackoverflow.com/questions/23125497/how-to-execute-a-sequence-of-events-in-angular-using-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!