0

I have a promise and I need to call a function in my $scope. If I call the function outside the then it works but actually I need to call it after the promise has been resolved, inside the then. Unfortunately the $scope is unavailable at that stage

traverseTree(items).then(function(data){
   $scope.$apply(function () {
       $scope.myArray.push(data);
   });
});

I didn't find any solution to this problem, actually I don't even know what keywords to use for searching a solution online

EDIT

Here the stacktrace, the exception get thrown at $scope.$apply

enter image description here

$scope looks valorized correcly inside the then

Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159

2 Answers2

2

Your $scope is accessible, but the issue is that you are trying to manually run digest cycle whilst it already in progress, so just remove the apply, it will be fine. You should have smth like this

traverseTree(items).then(function(data){
   $scope.myArray.push(data);
});
Y.Puzyrenko
  • 2,166
  • 1
  • 15
  • 23
1

You error is, in fact, because you are trying to run a new digest cycle while another is already executing.

If you are not doing anything outside Angular's reach, you don't need to manually call the $apply, Angular automatically does it for you.

For more information, take a look at this other question.

tiagodws
  • 1,345
  • 13
  • 20