30

Can I have a $broadcast $on with multiple parameters, something like:

$scope.$broadcast('event',$scope.item, $scope.item);

Is it possible to have something like this or something similar in any case ?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
blaa
  • 801
  • 3
  • 16
  • 32

3 Answers3

62

Just put the parameters into an object:

$scope.$broadcast('event', { a: item1, b: item2 })

Then access them from the second argument to the callback:

$scope.$on('event', function(event, opt) {
 // access opt.a, opt.b
});

Or if using ES2015 syntax you can unpack the arguments:

$scope.$on('event', (event, {a,b}) => {
 // access them just as a, b
});
Duncan
  • 92,073
  • 11
  • 122
  • 156
3

Documentation says:

'Optional one or more arguments which will be passed onto the event listeners'

$rootScope.$emit(event_name, p1, p2, p3);
Phil3992
  • 1,059
  • 6
  • 21
  • 45
user1920925
  • 672
  • 6
  • 5
-1
$scope.$broadcast('broadcast-my-event', anyVariable);
anyVariable = {key1: value1, key2: value2};
// or
anyVariable = [value1, value2, value3];
  • 4
    This doesn't explain how to use multiple parameters – RhysD Feb 05 '20 at 15:58
  • See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct it doesn't explain why it solves the problem or should be the selected answer. We should educate in addition to help solve the problem. – the Tin Man Feb 06 '20 at 23:53