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"');
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 $digest
ed) 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With