n1313
n1313

Reputation: 21391

Is there a way to subscribe to multiple events at once in AngularJS?

Is there a way to pass several event names to $on method and to assign same callback to all of those events?

Basically, I am looking for something like $scope.$on('event1 event2 event3', sameCallback);. Documentation says that eventName is a string and doesn't mention allowing multiple event names there. Should I write my own convenience method just for that?

Upvotes: 0

Views: 506

Answers (2)

Dima Shevtchuk
Dima Shevtchuk

Reputation: 55

try just wrap on default function. I thinks is a good idea set events:

context.on = function(events, callback) {
 var events_arr = events.split(" ");

 angular.each(events_arr, function(event) {

    $scope.$on(event, callback);

 },this)

}

this is crude, but i think you know what i mean

Upvotes: 1

lastboy
lastboy

Reputation: 576

You can code it yourself, something like that...

[{event: "event1", callback:function(){}}, {event:'event2'}].forEach(function(item) {
    scope.$on(item.event, (item.callback || function(){}))
});

Upvotes: 1

Related Questions