I have an angular controller as such:
app.controller('MyController', function($scope) {
var dao = new MyDao();
var something = dao.getSomething();
$scope.something = something;
// update view
var somethingElse = dao.getSomethingElse();
$scope.somethingElse = somethingElse;
// update view again
});
This controller is tied to a view through a routing config. Method getSomething() and getSomethingElse() can take several seconds to execute, so I'd like to update the view as soon as each method returns it data. I read that I should be able to do this by adding $scope.$apply();
where the comments are, but angular is throwing an error: Error: [$rootScope:inprog]
. Can someone explain why or provide a better alternative? Thanks
You are trying to trigger a digest cycle (via $apply()
) while one is already happening.
You can use $timeout()
it will trigger a digest if needed or continue normally if one is already in progress.
$timeout(function() {
// anything you want can go here and will safely be run on the next digest.
})
You can also check if $scope.$$phase
is false (meaning angular is not in the middle of a digest) before using $apply()
, but that is unadvised.
if(!$scope.$$phase) {
//$digest or $apply
}