尽管有一个类似的问题Data is not getting updated in the view after promise is resolved但我已经在使用这种方法,并且 View 没有更新。
我有一家工厂:
'use strict';
myApp
.factory('Factory1', [ '$http','$q','$location', '$rootScope', 'Service', function($http, $q, $location, $rootScope, Service){
return {
checkSomething: function(data){
var deferred = $q.defer(); //init promise
Service.checkSomething(data,function(response){
// This is a response from a get request from a service
deferred.resolve(response);
});
return deferred.promise;
}
};
}]);
我有一个 Controller :
'use strict';
myApp
.controller('MyCtrl', ['$rootScope', '$scope', '$location','Service', 'Factory1' function($rootScope, $scope, $location, Service, Factory1) {
if(Service.someCheck() !== undefined)
{
// Setting the variable when view is loaded for the first time, but this shouldn't effect anything
$scope.stringToDisplay = "Loaded";
}
$scope.clickMe = function(){
Factory1.chechSomething($scope.inputData).then(function(response){
$scope.stringToDisplay = response.someData; // The data here is actually being loaded!
});
};
}]);
以及 View :
<div class="app " ng-controller="MyCtrl">
{{stringToDisplay}}
<button class="button" ng-click="clickMe()">Update display</button>
</div>
但是当我单击“更新显示”按钮时, View 中的数据并未更新。为什么?
即使 $scope
正在加载数据
编辑:
嗯,当我尝试 $scope.$apply()
时似乎出现错误,它显示:
[$rootScope:inprog] $digest already in progress
最佳答案
这可能是摘要循环问题。您可以尝试:
...
$scope.stringToDisplay = response.someData;
$scope.$apply();
...
为了完整起见,here是 $scope.$apply
的一个很好的总结。
编辑:我尝试重现 this fiddle 中的错误,但似乎找不到任何问题。它可以在没有 $scope.$apply
的情况下完美运行。我使用 setTimeout
来模拟异步操作,该操作本身不应触发摘要周期。
关于angularjs - promise 解决后,范围未在 View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22036414/