What's the correct way to communicate between controllers in AngularJS?

前端 未结 19 2466
猫巷女王i
猫巷女王i 2020-11-21 22:02

What\'s the correct way to communicate between controllers?

I\'m currently using a horrible fudge involving window:

function StockSubgro         


        
19条回答
  •  一整个雨季
    2020-11-21 22:50

    I've actually started using Postal.js as a message bus between controllers.

    There are lots of benefits to it as a message bus such as AMQP style bindings, the way postal can integrate w/ iFrames and web sockets, and many more things.

    I used a decorator to get Postal set up on $scope.$bus...

    angular.module('MyApp')  
    .config(function ($provide) {
        $provide.decorator('$rootScope', ['$delegate', function ($delegate) {
            Object.defineProperty($delegate.constructor.prototype, '$bus', {
                get: function() {
                    var self = this;
    
                    return {
                        subscribe: function() {
                            var sub = postal.subscribe.apply(postal, arguments);
    
                            self.$on('$destroy',
                            function() {
                                sub.unsubscribe();
                            });
                        },
                        channel: postal.channel,
                        publish: postal.publish
                    };
                },
                enumerable: false
            });
    
            return $delegate;
        }]);
    });
    

    Here's a link to a blog post on the topic...
    http://jonathancreamer.com/an-angular-event-bus-with-postal-js/

提交回复
热议问题