简体   繁体   中英

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

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 .

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

 $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);
    });
$scope.$emit('MyEvent', args);

从第一个控制器,并在第二个控制器接收:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM