Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between $scope.apply(); and $scope.apply(function(){});

Tags:

angularjs

Take this code:

$scope.$apply(function(){
    $scope.foo = 'test';
});

Versus this one:

$scope.foo = 'test';
$scope.$apply();

What is the difference between those two? I tried searching but could not find any information about this.

Or even this approach:

$scope.$apply('foo = "test"');
like image 746
subZero Avatar asked Nov 06 '13 13:11

subZero


2 Answers

The article you referenced in your comment is correct. The only difference, is that if you pass in a function, that function will be "applied" (or $digested) before the rest of the $digest cycle. So if you're wanting Angular to recognize your specific change immediately (meaning before it evaluates all other changes), you should pass in a function. Otherwise, there is no difference between $scope.$apply() and $rootScope.$digest().

The article says the following:

What is $apply? Simply put, it's a wrapper around $rootScope.$digest that evaluates any expression passed to it prior to calling $digest(). That's it. So, if you're calling it by itself without passing an argument to it, you may as well just call $digest().

Hope that helps.

like image 154
tennisgent Avatar answered Oct 18 '22 14:10

tennisgent


Its simple, consider the below example

$scope.$apply(function(){
   //lets say we write some conventional JS code like
   //make an ajax call using $.ajax() of jquery
   // the code runs in angular context and exception will be thrown if any error
});

where as

$.ajax({
   // in response update the $scope.foo = 400/0 ;
}); 
$scope.$apply();
//no exception will be thrown by angular, because its unaware of what you do outside its context
like image 20
Libu Avatar answered Oct 18 '22 14:10

Libu