13

I have the following set up:

stApp.controller('AdminTableController', ['$rootScope', '$scope', 'gridService', 
            function ($rootScope, $scope, gridService) {
    $scope.$watch('tableData.$pristine', function (newValue) {
        $rootScope.broadcast("tableDataUpdated", {
            state: page.$pristine
        });
    });
}])

stApp.controller('AdminGridController', ['$rootScope', '$scope', 'gridService',
            function ($rootScope, $scope, gridService) {
    $rootScope.on("tableDataUpdated", function (args) {
        //args.state would have the state.
        alert(args.state);
    });
}])

When I run this code I am getting a message:

Object #<Object> has no method 'on'

Note that I tried this with both $rootScope.on and $scope.on

1
  • 2
    Actually, you need to use ´$on´ instead of ´on´ and $broadcast instead of broadcast Commented Jul 21, 2013 at 19:12

4 Answers 4

21

You must have meant $broadcast and $on (rather than broadcast and on), that is:

$rootScope.$broadcast("tableDataUpdated", { state: page.$pristine });
// ...
$rootScope.$on("tableDataUpdated", function (args) {
// ...

It's worth noting that $broadcast is used to delegate events to child or sibling scopes, whereas $emit will bubble events upwards to the scope's parents, hence;

When choosing $broadcast (and not $emit), one should either inject the root scope for tying the $on (as you nicely did) or call $on on the receiver's isolated scope, be it a child scope of the dispatcher.

See this post for elaboration on $emit and $broadcast.

Sign up to request clarification or add additional context in comments.

Comments

7

If the event listener is in a child scope: $scope.$broadcast('MyEvent', args);

If the event listener is in a parent scope: $scope.$emit('MyEvent', args);

You could avoid any confusion by using $broadcast on $rootScope, since $rootScope is the parent of all scopes in an Angular application: $rootScope.$broadcast('MyEvent', args);

Whether you use $emit or $broadcast, the receiving controller listens with $scope.$on('MyEvent', function() {});

2 Comments

I think it is the other way around. $emit sends upwards from child scope to parent scope. $broadcast goes from parent to child. See docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit
You're absolutely right -- I wrote listener instead of emitter, but I've fixed it here so they're reversed. Thanks!
2
 $rootScope.on("tableDataUpdated", function (args) {
        //args.state would have the state.
        alert(args.state);
    });

should be

 $rootScope.$on("tableDataUpdated", function (args) {
        //args.state would have the state.
        alert(args.state);
    });

Comments

0
$scope.$emit('MyEvent', args);

from first controller, and receive in second controller:

$scope.$on('MyEvent', function() {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.