如何确保在转到视图之前,作用域变量更新并绑定到AngularJS中。
如何确保在转到视图之前,作用域变量更新并绑定到AngularJS中。
在我的代码中,有一个作用域变量叫做$scope.detailsPresent,它基本上只是检查是否有数据,并根据结果显示不同的页面。
问题是,当我执行console.log($scope.detailsPresent)时,根据数据是否存在,值是正确的,如果没有数据,值应该为false,如果有数据,值应该为true。
但是视图还没有绑定这个值,所以在视图上这个值还没有更新,因此它不显示正确的页面。我该如何确保该值在视图中更新?我尝试了$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); }
我的HTML文件my.html:
我已经为这个问题努力了大约6天,但是还没有成功。非常感谢任何帮助。
问题的原因是使用了ng-if指令,导致scope变量在更新和绑定到视图之前出现问题。解决方法是将ng-if指令改为ng-show指令,这样可以避免调用$scope.$apply()方法时出现错误。下面是一种可能的解决方案:
首先,将ng-if指令改为ng-show指令:
Content
接下来,确保在使用$scope.$apply()方法之前没有其他的$scope.$apply()方法调用,或者使用$scope.$applyAsync()方法。
详细解决方法可以参考这个答案:[点击这里](https://stackoverflow.com/questions/22346990#answer-22349659)