user1943020
user1943020

Reputation:

How can I send a message from one controller to another in AngularJS?

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

Upvotes: 13

Views: 16410

Answers (4)

Jake McGuire
Jake McGuire

Reputation: 304

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() {});

Upvotes: 7

Eliran Malka
Eliran Malka

Reputation: 16263

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.

Upvotes: 21

rajasaur
rajasaur

Reputation: 5460

 $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);
    });

Upvotes: 2

0xAX
0xAX

Reputation: 21817

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

from first controller, and receive in second controller:

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

Upvotes: 0

Related Questions