2

According to this answer I just want fire event from controller to another

Call a method of a controller from another controller using 'scope' in AngularJS

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

But I don't use $scope in my application, just controllerAs and this. There is a way to fire event without inject the scope ? Or should I inject $scope anyway ?But I read in another answer that using both scope and controllerAs is bad practice.

Community
  • 1
  • 1
amdev
  • 3,010
  • 3
  • 35
  • 47

2 Answers2

1

It's not possible to register an $emit or $broadcast event without $scope or $rootScope being injected in the controller.

It is indeed bad practice to use $scope variables and functions since the instance of your controller is already injected inside the $scope with the controllerAs syntax.

But there is not other choice than injecting scope objects if you want to use these events.

However you shouldn't use $emit or $broadcast events just to share data. These events are used for application wide information (like user has logged in or logged out...etc.)

A good practice when using angular events is to prefer $rootScope.$emit because $scope relies on the hierarchy of your components.

For example:

$scope.$emit will emit to the parent component.

$scope.$broadcast will broadcast to children components.

Then $rootScope.$broadcast will broadcast events to the rootScope as well as the scope (which may make your code messy real quick)

$rootScope.$emit is to be preferred as it registers the event application wide and makes it available to the rootScope only. ($rootScope.$on)

Another good practice is to unbind your custom events. Whenever a component or directive is unloaded/destroyed, the event listener will still reside inside rootScope resulting in possible memory leaks.

To unbind an event:

var unbind = $rootScope.$on('logout', function(event, data) {
    console.log('LOGOUT', data);
});
$scope.$on('$destroy', unbind);
gyc
  • 4,300
  • 5
  • 32
  • 54
0

I think that generally overuse of $broadcast and $emit is a bad practice too. If you don't want to use the $scope, why not moving the logic handled by events to a service?

Piotr Jaworski
  • 584
  • 1
  • 5
  • 20
  • 1
    I use service, but anyway when MyController2 of view2 is changing state, I want MyController1 to update for refresh view1. And Controller2 can't know about service value change, unless i use $watch or $broadcast to fire event so i back to my question :p – amdev Jul 06 '16 at 12:38