What is the $ scope? $ apply?

3

I've seen in a code the $ scope. $ apply that uses AngularJS, what's it for? In the context you are in it is this way:

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

1 answer

10

In Angular 1.x, current version, changes made "out of angular" are not identified by it, $scope.apply() or $scope.digest() do the job of asking angular to revise their variables for external modifications. Note that in this code example, the function inside apply looks in the structure of the page with the document.getElementById (which is a mean outside the angle), an element that is possibly managed by the angle and changes it.

It's important to warn, that $scope.apply() says to angular, "Hey, I've changed something! Turn around to find out what it was." then it will search across the root for elements managed by the possible changes, which can be pretty bad in terms of performance. $scope.digest() does the same thing, but only the current scopo down.

More information here in the documentation: link $ rootScope.Scope # $ apply

Just to complement, I mentioned Angular 1.x because in Angular 2, according to the documentation these modifications out of scope, will be detected automatically.

    
05.11.2015 / 17:32