1

I have a service that make

$rootScope.$broadcast('myEvent', somedata)

from time to time. In controller I do

$scope.$on('myEvent', function (evt, somedata) { $scope.data = somedata })

The question is if I omit

if (!$scope.$$phase) { $scope.$apply(); }

in controller's event listener, then view won't change. Why is that? Is there any better way to do it?.

BKM
  • 6,949
  • 7
  • 30
  • 45
Ivan Demchenko
  • 457
  • 3
  • 13

1 Answers1

0

It is because $apply is a lazy worker and will do the job only there is enough stuff to refresh. You can't control when, unless you explicitly call $scope.$apply.

Yes, there is a better way to do this : call safeApply. Because calling explicitly many $apply can cause conflicts. There is no official safeApply implementation, so can choose you poison :

Community
  • 1
  • 1
bdavidxyz
  • 2,492
  • 1
  • 20
  • 40
  • Yes, I understand this. My question is why my view doesn't update when I change the scope on message. `$scope.$on('message', function (e, data) {` ` $scope.someData = data;` ` // without this if view won't update` ` if (!$scope.$$phase) {` ` $scope.$apply();` ` }` `});` – Ivan Demchenko Aug 30 '13 at 10:40
  • I mean, why should I call `$apply` every time I got an event, that has been broadcasted from the `$rootScope`? – Ivan Demchenko Aug 30 '13 at 10:48
  • Yes, it falls in the scope where you have to call $apply. Don't call $apply all the time, but if there is such an unexpectable event (event from rootscope is one of them), then you'll have to call it anyway. – bdavidxyz Aug 30 '13 at 13:06