setInterval和更新值AngularJS [英] setInterval and updating values AngularJS

查看:116
本文介绍了setInterval和更新值AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于更改变量的值我希望在我的html中显示错误消息。我从我的角度代码调用api,如果它返回错误,我已经设置了一个setInterval函数,该函数应该将bookingData.tracking_id更新为false,然后在html中显示错误消息。这应该很容易,但是将它与setInterval结合起来有点困难。

Based on changing the value of a variable I wish to display an error message in my html. I call an api from my angular code, and if it returns an error, I have set up a setInterval function that should update bookingData.tracking_id to false and then show an error message in the html. This should be very easy but combining this with setInterval is proving slightly difficult.

这是angular / javascript

Here is the angular/javascript

this.confirmTrackingTest = function () {
  TestService.finalPackageCheck({tracking_id: controller.bookingData.tracking_id}).$promise.then(function (data) {
    return data;
  }).catch(function (err) {
    var i = 0;
    var interval = setInterval(function () {
      i += 1;
      if (i === 3) {
        if (err.statusText === "Not Found") {
          controller.bookingData.showErrorMessage = true;
        }
        clearInterval(interval)
      }
    }, 2000);
    console.log(controller.bookingData.showErrorMessage)
  });
}

this.bookingData = {
  showErrorMessage: false,
  tracking_id: 1
};

这是 html

{{Packs.bookingData.showErrorMessage}}
<div class="alert alert-danger" role="alert" ng-if="Test.bookingData.showErrorMessage">
  <p>Please show this message</p>
</div>

{{Packs.bookingData.showErrorMessage}} 显示为false,以便在html中重新显示。

The {{Packs.bookingData.showErrorMessage}} shows false so that is recongised in the html.

如果需要任何进一步的信息,请告诉我。

Please let me know if any further information is required.

推荐答案

这正是Angular众神发明 $ interval 的原因,以消除手动使用<$ c的需要$ c> $ apply 。

This is exactly the reason why the Angular gods invented $interval in order to remove the need to manually use $apply.

所以你要么叫 $ scope。$ apply 在回调中或你使用 $ interval (不要忘记将它包含在依赖注入的参数列表中)

So either you call $scope.$apply inside the callback or you use $interval (don't forget to include it in the parameter list for depedency injection)

这篇关于setInterval和更新值AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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