setInterval and updating values AngularJS

给你一囗甜甜゛ 提交于 2019-12-20 04:52:33

问题


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.

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
};

Here is the html:

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

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

Please let me know if any further information is required.


回答1:


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

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)



来源:https://stackoverflow.com/questions/32629939/setinterval-and-updating-values-angularjs

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