即使对此Data is not getting updated in the view after promise is resolved存在类似的问题,但我已经在使用此方法,并且视图未更新。
我有一家工厂:
'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;
}
};
}]);
我有一个控制器:
'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!
});
};
}]);
观点:
<div class="app " ng-controller="MyCtrl">
{{stringToDisplay}}
<button class="button" ng-click="clickMe()">Update display</button>
</div>
但是当我点击“更新显示”按钮时,视图中的数据没有更新。为什么?
即使$scope
正在加载数据
编辑:
嗯,我尝试$scope.$apply()
时似乎收到错误,并说:
[$rootScope:inprog] $digest already in progress
答案 0 :(得分:12)
这可能是一个摘要周期问题。你可以尝试:
...
$scope.stringToDisplay = response.someData;
$scope.$apply();
...
为了完整起见,here是$scope.$apply
的一个很好的总结。
修改:我尝试在this fiddle中重现错误,但似乎无法找到任何问题。没有$scope.$apply
,它可以完美运行。我使用setTimeout
来模拟异步操作,这不应该单独触发摘要周期。
答案 1 :(得分:0)
尝试使用此功能代替您的功能
$scope.clickMe =$scope.$apply(function(){
Factory1.chechSomething($scope.inputData).then(function(response){
$scope.stringToDisplay = response.someData; // The data here is actually being loaded!
});
});