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

问题描述

我在查看的div,我想执行的NG-点击(函数),它变成了div来'颜色'30秒背景如果没有采取行动然后60秒钟,然后更改为彩色b',如果不采取任何行动超过120秒只是隐藏分区(这可以通过添加/删除类以及完成)

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.

上的任何帮助将是巨大的AP preciated。
谢谢。

Any help on that would be hugely appreciated.Thanks.

推荐答案

我会在范围使用一个变量来保存状态,链接方法是 $超时 s到各州之间移动。这样,会被点击的元素:

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 就是这样什么都不做的函数。这是一个稍微个人preference,但我觉得它更容易一点,看看在那里的回调传递给 $超时什么都不做活动的流程,所有的动作范围总是在承诺的然后成功回调。

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:

<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.

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

11-01 19:02