2

So I have two directives (Timeline and Displayer) instanciated in a controller.

When a click happens on Timeline, it $emits a TimelineClicked event to the controller .

The controller $on('TimelineClicked', cb), $broadcasts an UpdateDisplay event to Displayer .

I have two situations here :

  1. onUpdateDisplay can be called during a $digest cycle, for example, on load, which updates UI
  2. but when it comes from TimelineClicked apparently it is not $digested.

Hence wrapping the method with $apply like so:

$scope.onUpdateDisplay = function($event, activeObjects) {
    $scope.$apply(function() {
        //$scope values modification
    });
};

Will trigger an $apply already in progress error when in situation 1 and not it 2 .

I don't consider doing something like if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') which is way too dirty IMHO.

  • How should two directives talk together and make sure their scope is always up-to-date?
  • Does the $apply cycle waits for events callbacks to finish?
  • Should I wrap the apply somewhere else (around the $on('TimelineClicked', cb))?

I have tried several configuration without success...

WhiteLine
  • 1,919
  • 2
  • 25
  • 53
Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206
  • One option is, instead of calling `$scope.$apply` directly, you can use `$timeout(function(){ /* do something */ })` to ensure that it's safe. – james May 07 '15 at 10:45
  • It also sounds very hacky to me. But I tried ... without success. – Augustin Riedinger May 07 '15 at 11:44
  • Please show us some relevant code. Works for me: http://jsfiddle.net/uLbv5n4k/ – Sergiu Paraschiv May 07 '15 at 11:46
  • Been trying to reproduce in a Fiddle. Here's mine: http://jsfiddle.net/206e2cmh/1/ But it also works in the fiddle. Plus in between it got fixed on my code, I hardly know what changes I made for that. Sorry, all of this is not very helpful... – Augustin Riedinger May 07 '15 at 14:18
  • 1
    True, but unfortunately sometimes it's unavoidable, as discussed here http://stackoverflow.com/questions/23070822/angular-scope-apply-vs-timeout-as-a-safe-apply You should aso take a look at this https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply%28%29 – james May 08 '15 at 13:51

0 Answers0