What is $Scope for. $apply ?

Asked

Viewed 8,620 times

5

I saw in a code $Scope. $apply that uses Angularjs, what does it serve ? In the context it is in this way:

var a = function(param){
            $scope.$apply(function(){
                var image = document.getElementById('img');
                image.src = "data:image/jpeg;base64," + param;
        });
    };

1 answer

13

In Angular 1.x, current version, changes made "outside" of the angular are not identified by it, $scope.apply() or $scope.digest() do the job of asking the angular to review their variables in search of external modifications. Note that there in this code example, the function within the apply searches the page structure with the document.getElementById (which is a medium outside the angular), an element that is possibly managed by the angular and alters it.

It is important to warn, that $scope.apply() says at the angle, "Hey, I changed something! Turn around and find out what it was." then it will search across the root of elements managed by the possible changes, which can be quite bad in terms of performance. The $scope.digest() does the same thing, but only from the current scope down.

More information here in the documentation: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

Just to complement, I cited Angular 1.x because in Angular 2, according to the documentation these changes outside of Cope, will be detected automatically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.