Angular控制器中的操作顺序没有以正确的方式工作

sequence of operations in Angular controller not working in a right way

本文关键字:方式 工作 控制器 操作 顺序 Angular      更新时间:2023-09-26

我有一个页面,用户在其中输入初始数据,然后单击"计算"。点击后,在进行计算时,应该会出现一个带有加载微调器的gif图像。一旦结果准备好,gif图像就会消失,结果就会显示在页面上。这是我正在使用的代码:

$scope.loading=false; //initially the img is invisible    
$scope.calc=function(){
      $scope.loading=true;//make the img visible
      var result=MyService.calc(input_data); //processing data
      $scope.result=result;
      $scope.loading=false;//hide the img
}

HTML图像的定义如下:

<div class="span1">
  <div ng-if="loading"><img ng-src="img/ajax-loader.gif"></div>
</div>

这是意料之中的事情。但事实上,它的工作原理如下:单击"计算"后,图像不会出现,经过一段时间的计算后,图像会显示并逃逸。

计算是在服务中进行的。

怎么了?我已经尝试在服务中创建一个$q.defer(),它会以结果进行解析。然后在控制器中显示promise.then函数内部的结果。但它不起作用。

为此使用$timeout。模型在执行的过程中没有得到更新

JavaScript

$scope.calc=function(){
      $scope.loading=true;//make the img visible
      $timeout(function(){
          var result=MyService.calc(input_data); //processing data
          $scope.result=result;
          $scope.loading=false;//hide the img
      });
}

$timeout必须像$scope一样注入依赖项)