Vitalii
Vitalii

Reputation: 1812

How to track events on $scope.$broadcast?

I'm using angular-timer and I'm just a little confused how to track its events. For example, I want to do something after time is up, but I can't see any events on console log.

  vm.add20Seconds = function() {
    $scope.$broadcast('timer-add-cd-seconds', 20);
  }

  $scope.$on('timer-add-cd-seconds', function (event, data) {
    console.log(data); // 'Some data'
  });

The console is empty.

https://github.com/siddii/angular-timer/blob/master/examples/angularjs-add-countdown-seconds.html

Upvotes: 1

Views: 627

Answers (2)

macrog
macrog

Reputation: 2105

if you are looking for a good article about using the scope tree As A Publish And Subscribe (Pub/Sub) mechanism in angularJS please check this link

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

As the code given in link is not seems to be updated, I think you changed it to use controllerAs syntax. So your button html will use vm alias while calling controller method. Assuming you used ng-controller="MyAppController as vm"

Markup

<button type="button" ng-click="vm.add20Seconds()">Add 20 Seconds</button>

Else wanted to use $scope in your controller then simply change method to $scope.add20Seconds instead of vm.add20Seconds

Update

To get call a function after 20 seconds over, you could use $timeout service here, that will call and specified callback when mentioned $timeout completed.

Code

vm.add20Seconds = function() {
   $scope.$broadcast('timer-add-cd-seconds', 20);
}

var myCallbackAfterTimeout = function(){
   //add your code.
}

$scope.$on('timer-add-cd-seconds', function (event, data) {
 console.log(data); // 'Some data'
 $timeout(myCallbackAfterTimeout, data); //data is nothing but timeout milliseconds
});

Include $timeout dependency in your controller before using it.

Upvotes: 1

Related Questions