5

At some point after a user action I would like to cause a digest to occur, so the UI reflects a change in the data-model backing it.

I have a service that performs some change in a callback (asynchronously).

I understand that $scope only makes sense in the context of a controller. Can I achieve the same effect by performing $apply() on the $rootScope?

I have seen code that checks for $$phase or similar related to avoiding digest errors, what checks should I perform in order to trigger a digest safely?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

1 Answers1

8

See this answer: Running $apply on $rootScope vs any other scope

You can call $rootScope.$apply() outside of a controller (i.e. in a service) in order to trigger a digest loop.

Alternatively, you could consider using $broadcast and $on to send a notification to other parts of your app when something needs refreshing. (See Understanding Angular’s $scope and $rootScope event system $emit, $broadcast and $on)

// in a service
$rootScope.$broadcast('myCustomEvent', {
  someProp: 'foobar'
  // other data
});

// in a controller or another service
$scope.$on('myCustomEvent', function (event, data) {
  console.log(data);
  // do something with this event
});
Community
  • 1
  • 1
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
  • Do I need to guard against calling `apply()` during an existing digest? – Ben Aston Feb 02 '15 at 22:48
  • See some of the discussion here: http://stackoverflow.com/a/18626099/3191599 As I understand, there's rarely a need to call `$apply()` outside of working with non-Angular JS components. A broadcast/on or even a (light) `watch` should do the trick in most cases. Another reference: http://stackoverflow.com/a/20847904/3191599 – Nate Barbettini Feb 03 '15 at 00:04