SetTimeout 中的 SetTimeout 不触发

4
我正在尝试创建一个按钮,以向执行的操作提供反馈。在Angular中,我正在向服务器发出put请求-此时,我更改按钮的状态以指示这一点-然后当我收到响应时,我再次更改按钮的状态以反映成功或失败1.5秒,然后将其重置回按钮点击之前的状态。此时还应显示反映成功或失败的消息,并在另外5秒钟后执行其他操作。如果是失败,则应隐藏显示的消息,并在成功时重定向页面。我无法使最后一部分起作用。
因此,我的问题是,我是否应该能够在另一个setTimeout中放置setTimeout?
以下是我的代码(在按钮函数内部):
$scope.resetPassword = function() {

    $scope.ShowSuccessMessage = false;
    $scope.ShowFailedMessage = false;

    var querystring = $location.search();

    var dataObject = { email1 : $scope.formEmail1, email2 : $scope.formEmail2, password1: $scope.formPassword1, password2: $scope.formPassword2, token: querystring.token };

    var responsePromise = $http.put("/myurl/", dataObject, {});

    //  change colour and icon of reset button for 1.5 sec
    var $el           = $("#resetPassword");
    var resetButton   = 1500;
    var resetMessage  = 5000;
    var originalColor = $el.css("background");
    var originalIcon  = $el[0].firstChild.className; // get first html element in the button, which is the <i>

    $el[0].firstChild.className = "fa fa-circle-o-notch fa-spin";

    responsePromise.success(function(dataFromServer, status, headers, config) {
      $el.css("background", "#02c66c");
      $el[0].firstChild.className = "fa fa-check-circle";

      $scope.ShowSuccessMessage = true;

      ResetButton($el, $scope, originalColor, originalIcon, resetButton, true, resetMessage);
    });

    responsePromise.error(function(dataFromServer, status, headers, config) {
      $el.css("background", "#d9534f");
      $el[0].firstChild.className = "fa fa-times-circle";

      $scope.ShowFailedMessage = true;

      ResetButton($el, $scope, originalColor, originalIcon, resetButton, false, resetMessage);
    });
};

ResetButton = function(el, scope, originalColor, originalIcon, resetButton, success, resetMessage)
{
  setTimeout(function() {
    el.css("background", originalColor);
    el[0].firstChild.className = originalIcon;

    ChangeMessageOrChangeLocation(scope, success, resetMessage);
  }, resetButton);
}

ChangeMessageOrChangeLocation = function(scope, success, resetMessage)
{
  if(success) {
    setTimeout(function(){
      window.location = '/signin';
    }, resetMessage);
  }
  else {  
    setTimeout(function() {
      scope.ShowFailedMessage = false;
    }, resetMessage);
  }
}

编辑:这里有一个实时示例:贪婪的喜鹊(请注意,这是一个正在进行中的工作,因此网站上并不是所有功能都能正常运行)。只需单击更改密码按钮即可...


1
你应该能够级联它们。 - Ali Naci Erdem
在超时内调用另一个超时并没有问题,这只是一个调用另一个函数的函数。 - peernohell
@peernohell 这就是我想的,你知道为什么我的第二个setTimeout没有触发吗? - Ebbs
1
可能是重复的问题:AngularJS值不会随setTimeout改变 - hon2a
1个回答

1

winfow.setTimeout在Angular的脏检查周期之外执行,因此视图不会更新。在scope.ShowFailedMessage = false;之后添加scope.$apply()或使用$timeout服务代替setTimeout。第二种方法更好。

请在此处查看$timeout服务文档:$timeout


感谢您的解释,非常感激! - Ebbs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接