Skip to content Skip to sidebar Skip to footer

Broadcasting An Event In Angular: How To Alter Flow By Subscribing To Event?

I have the following logic in my program: User clicks some button. Modal dialog appears. Once it is closed, promise is returned (I am using $modal from angular-bootstrap) and som

Solution 1:

You could use the $event object to achieve what you want.

When broadcasting, an $event object will be created and sent along to all listeners. You have a chance here to store any return value you want into the $event object (or using a built-in preventDefault() mechanism) in one of the listeners like this:

$scope.$on('aboutToOpenDialog', function ($event) {
  // you could use built-in preventDefault() and defaultPreventedif ($scope.noModal) {
    $event.preventDefault();
  }

  // or just assign any values to some property and get it back later.$event.someReturnValue = $scope.noModal ? 'noModal' : 'showModal';
});

and when the broadcasting is finished, the $broadcast() will return the same $event object, and you can check values on it.

$scope.openDialog = function() {
  var$event = $rootScope.$broadcast("aboutToOpenDialog");

  if (!$event.defaultPrevented) {
    // $modal.open() here
    console.log('open modal');
  } else {
    console.log('suppress modal');
  }

  // orif ($event.someReturnValue === 'showModal') {
    // $modal.open() here
    console.log('open modal again');
  }
};

Example plunker:http://plnkr.co/edit/GjsfoqOLjEAqMzoa8IHp?p=preview

Hope this helps.

Post a Comment for "Broadcasting An Event In Angular: How To Alter Flow By Subscribing To Event?"