dylan
dylan

Reputation: 314

angularjs: $apply(fn) better than $apply()

I am reading http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/

directive link function:

element.bind('click', function() {
  scope.foo++;
  scope.bar++;

  scope.$apply();
});

a better way for using $apply:

element.bind('click', function() {
  scope.$apply(function(){
    scope.foo++;
    scope.bar++;
  });
});

What’s the difference? The difference is that in the first version, we are updating the values outside the angular context so if that throws an error, Angular will never know. Obviously in this tiny toy example it won’t make much difference, but imagine that we have an alert box to show errors to our users and we have a 3rd party library that does a network call and it fails. If we don’t wrap it inside an $apply, Angular will never know about the failure and the alert box won’t be there.

Confusion: Why angular need to know error, i just need to show it for users. for example, there is an ajax request in link fn of directive, I just need to tell what happened if fails.

Upvotes: 1

Views: 773

Answers (1)

kunsingh
kunsingh

Reputation: 254

TAngular $scope has a function called $apply() which takes a function as an argument. AngularJS says that it will know about model mutation only if that mutation is done inside $apply(). So you simply need to put the code that changes models inside a function and call $scope.apply(), passing that function as an argument. After the $apply() function call ends, AngularJS knows that some model changes might have occurred. It then starts a digest cycle by calling another function —- $rootScope.$digest() — which propagates to all child scopes. In the digest cycle watchers are called to check if the model value has changed. if a value has changed, the corresponding listener function then gets called. Now it’s upto the listener how it handles the model changes.

The Ajax call through Angular buildin $http the model mutation code is implicitly wrapped withing $apply() call, so you don’t need any additional steps.

Upvotes: 1

Related Questions