So, the theory is reasonable, if you only want to perform this magical action after you received these two events, was called at least once, then you probably want to use promises.
app.controller('ExampleOneController', [ '$log', '$scope', '$q', '$rootScope', function ($log, $scope, $q, $rootScope) { $scope.anotherAction1FiredCount = 0; var aDeferred = $q.defer(), bDeferred = $q.defer(); $scope.$on('e-1-a', function () { $log.log('Fired e-1-a'); aDeferred.resolve(); }); $scope.$on('e-1-b', function () { $log.log('Fired e-1-b'); bDeferred.resolve(); }); $q.all([aDeferred.promise, bDeferred.promise]).then(function () { $log.log('Fired another action 1!'); $scope.anotherAction1 = 'Hello World 1!'; $scope.anotherAction1FiredCount++; }); } ]);
As usual, I want to perform every time two things happen, so I tend to reset 'my promises.
app.controller('ExampleTwoController', [ '$log', '$scope', '$q', function ($log, $scope, $q) { $scope.anotherAction2FiredCount = 0; var aDeferred = $q.defer(), bDeferred = $q.defer(); $scope.$on('e-2-a', function () { $log.log('Fired e-2-a'); aDeferred.resolve(); }); $scope.$on('e-2-b', function () { $log.log('Fired e-2-b'); bDeferred.resolve(); }); var wait = function () { $q.all([aDeferred.promise, bDeferred.promise]).then(function () { $log.log('Fired another action 2!'); $scope.anotherAction2 = 'Hello World 2!'; $scope.anotherAction2FiredCount++; aDeferred = $q.defer(); bDeferred = $q.defer(); wait(); }); }; wait(); } ]);
Here is the working pluker!
Promises is life.
source share