在显示新页面angularjs之前绑定函数值

时间:2015-07-28 08:01:01

标签: javascript angularjs angularjs-scope

我试图在变量移动到视图之前将变量绑定到范围,但我的视图在变量有界之前显示。这是我的代码。

$scope.getListing = function() {
    var deferred = $q.defer(); 
    $scope.$applyAsync(function() {
      $rootScope.listingDetails =[];
      referralCasesGroupByCaseStatus.getListing($rootScope.userDetails.rows.item(2).value).then(function(data){
        $rootScope.listingDetails = data
        deferred.resolve($rootScope.listingDetails)

          if($rootScope.fromDashboard === false) {
            $scope.showCaseStatus(1); 
            $state.go('app.case_status')  
          }
          else {
            $scope.showCaseStatus($rootScope.statusNumber)
            $state.go('app.case_status')
            $ionicLoading.hide();
          }
      });
    }) 
    return deferred.promise; 
  };
  var changedNumber = 0;

  $scope.showCaseStatus = function(number) {
      var finishedPushingListings = false;
      $rootScope.listingByCaseStatus = [];
      $rootScope.caseStatusListings = [];

      if(changedNumber !== 0 && changedNumber !== number) {
        changedNumber = number;
      }
      else {
        if(changedNumber > 0) {
          $scope.$applyAsync($rootScope.detailsPresent = true);
        }
      }
      $scope.$applyAsync(function() {
        angular.forEach($rootScope.listingDetails, function(value, key) {
          if(value.real_estate_agent_assignment_status_id == number) {
            $rootScope.listingByCaseStatus.push(value);
          }
        });
      })

      $scope.$applyAsync(function() {
        if($rootScope.listingByCaseStatus == 0 || $rootScope.listingByCaseStatus == undefined || $rootScope.listingByCaseStatus == null) {  
          $rootScope.detailsPresent = true;  
          $rootScope.changeNumber = true; 
          finishedPushingListings = true;
        }  
        else {
          $rootScope.detailsPresent = false;
          $scope.noMoreItemsAvailable = false; 
          $rootScope.changeNumber = true;  
          finishedPushingListings = true;  
        }  
      }) 
  };

这里的主要问题是函数$scope.showCaseStatus($rootScope.statusNumber)在执行$state.go('app.case_status')之前没有完成执行,我希望它在跳转到$state.go('app.case_status')之前等待并完成执行。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

由于您使用的是$applyAsync(),因此功能效果是异步的。实现目标的一种方法是让showCaseStatus()返回一个承诺 - 并考虑到有两个异步块:

$scope.showCaseStatus = function(number) {
    var ..., d1, d2;

    ...

    d1 = $q.defer();
    $scope.$applyAsync(function() {
      angular.forEach($rootScope.listingDetails, function(value, key) {
        ...
      });
      d1.resolve();
    })

    d2 = $q.defer();
    $scope.$applyAsync(function() {
      ...
      d2.resolve();
    })

    // both promises must be resolved to continue
    return $q.all([d1.promise, d2.promise]);
};

然后来电者变成:

$scope.showCaseStatus($rootScope.statusNumber).then(function() {
    $state.go('app.case_status')
    $ionicLoading.hide();
});

一些注意事项:

  • 如果您不需要异步块,则可以删除它们并简化代码
  • 如果第二个异步块依赖于第一个异步块的结果,那么它们也应该同步