I am supporting a code made in AngularJS to make some modifications that have been requested, and I found the following code.
$scope.open($event, item){
if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
// Lógica del sistema
} else {
$timeout(function() {
$scope.open($event, item);
}, 10);
}
}
This topic of $apply
and $digest
I have not understood it very well and it generates the doubt of what is validating that condition? Why else
is a used in it setTimeout
to execute the same function again? It should be clarified that the function is executed by means of a ng-click
common and current.
Trying to understand the code a little more I changed the condition to the following form and it works the same.
$scope.open($event, item){
if ($scope.$$phase == null) {
// Lógica del sistema
} else {
$timeout(function() {
$scope.open($event, item);
}, 10);
}
}
What are the implications of using condition 1 or condition 2?
It
$scope
has a method called$apply
that is useful for when you update values outside the Angular environment it finds out that a change has occurred and executes a new digest cycle .The problem is that if you execute this method and at that moment a cycle is happening, it generates the following error
So you are forced to check this property in order not to have the error.
Your code checks for this condition and executes the logic only when the model is stable. Otherwise it recursively schedules a check in the next 10 milliseconds until it is possible to update the values.
Keep in mind that these properties are private, that is why they are indicated with
$$
and not with the usual$
one and they are not documented either , which makes you understand that you should use these techniques only when you need it and not indiscriminately.