如何确保一个作用域变量在查看angularjs之前被更新和绑定

How to ensure that a scope variable updates and binds before going to view angularjs

本文关键字:angularjs 更新 绑定 变量 确保 何确保 作用域 一个      更新时间:2023-09-26

在我的代码中,有一个名为$scope. detailpresent的作用域变量,它基本上只是检查是否有数据,并根据结果显示不同的页面。

发生的是,当我做console.log($scope. detailpresent)的值是正确的,基于是否有数据的值应该是假的,或者如果没有数据的值应该是真。

但是视图还没有绑定这个值,所以在视图上这个值还没有更新,因此它没有显示正确的页面。我如何确保值在视图中更新?我有尝试$scope.$apply(),但我得到一个错误,所以无论如何要做吗?

my_controller.js

angular.module('my.controllers')
.controller('ReferralCtrl', function($scope, $rootScope, $window, $state, $q, $timeout, referralCasesGroupByCaseStatus, AuthenticationService, $ionicLoading) {
$scope.detailsPresent = {myVar: false};
$scope.showCaseStatusFromDashboard = function(number) { 
    $timeout(function() {
      $scope.$applyAsync(function() {
        $rootScope.fromDashboard = true; 
      })
    }, 1000, true);
      $scope.showCaseStatus(number); 
  }
 $scope.showCaseStatus = function(number) {
    if(changedNumber !== 0 && changedNumber !== number) {
      changedNumber = number;
    }
    else {
      if(changedNumber > 0) {
        $scope.$applyAsync($scope.detailsPresent.myVar = true);
      }
    }
    $timeout(function() {
      $scope.$applyAsync(function() {  
        referralCasesGroupByCaseStatus.showCaseStatus(number, $rootScope.listingDetails).then(function(listingCaseStatus) {
          $rootScope.listingByCaseStatus = angular.copy(listingCaseStatus);
          if(listingCaseStatus == 0 || listingCaseStatus == undefined || listingCaseStatus == null) {
            $scope.detailsPresent.myVar = true;  
            $scope.changeNumber = true; 
            $state.go('app.case_status') 
          }  
          else {
            $scope.detailsPresent.myVar = false;
            $scope.noMoreItemsAvailable = false; 
            $scope.changeNumber = true; 
            $state.go('app.case_status') 
          } 
        })
      })
    }, 1000);
  }

my.html

<ion-view view-title="Case Status">
<ion-content>
    <div ng-if="detailsPresent.myVar">
      <ng-include src="template='no-listings'"></ng-include>
    </div>
    <div ng-if="!detailsPresent.myVar">
      <ng-include src="'templates/case-listings.html'"></ng-include>
    </div>
  </ion-content>
</ion-view>

我已经做了大约6天了,但没有成功的迹象。任何帮助都是非常感谢的。

这不是一个完整的答案,但我有一些建议。作为评论会更好,但是我还没有足够的声誉。

尝试将您的ng-if属性切换到ng-show属性。我意识到这将使包含的元素留在DOM中,但如果性能没有受到严重影响,它可能适合您。

另外,调用$scope.$apply()时出现错误的原因是因为您已经在调用$apply(),或者更确切地说是$applyAsync()

关于$apply()