如何使用 $timeout 在 Angular 中执行一系列事件 [英] How to execute a sequence of events in Angular using $timeout

查看:23
本文介绍了如何使用 $timeout 在 Angular 中执行一系列事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图中有一个 div,我想在 ng-click() 上执行一个函数,如果没有采取任何操作,该函数会将 div 的背景变为颜色 a" 30 秒然后 60 秒,然后更改为颜色 b",如果超过 120 秒没有采取任何行动,则隐藏 div.(这也可以通过添加/删除类来完成)

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 )

本质上,我希望以角度执行一系列 $timeouts,其中一个超时导致另一个超时.

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.

推荐答案

我会通过在作用域中使用一个变量来保存状态,并链接 $timeout 以在状态之间移动来处理它.所以在将被点击的元素上:

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>

在控制器中:

$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'
  });
}

angular.noop 只是一个什么都不做的函数.这是一个稍微个人的偏好,但我发现更容易看到传递给 $timeout 的回调什么都不做的活动流,并且作用域上的所有操作总是在 then promise 的成功回调.

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.

在背景 div 的模板中:

In the template for the background div:

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

然后在 CSS 中设置颜色:

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.

这篇关于如何使用 $timeout 在 Angular 中执行一系列事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆