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

前端 未结 19 2464
猫巷女王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:48

    The top answer here was a work around from an Angular problem which no longer exists (at least in versions >1.2.16 and "probably earlier") as @zumalifeguard has mentioned. But I'm left reading all these answers without an actual solution.

    It seems to me that the answer now should be

    • use $broadcast from the $rootScope
    • listen using $on from the local $scope that needs to know about the event

    So to publish

    // EXAMPLE PUBLISHER
    angular.module('test').controller('CtrlPublish', ['$rootScope', '$scope',
    function ($rootScope, $scope) {
    
      $rootScope.$broadcast('topic', 'message');
    
    }]);
    

    And subscribe

    // EXAMPLE SUBSCRIBER
    angular.module('test').controller('ctrlSubscribe', ['$scope',
    function ($scope) {
    
      $scope.$on('topic', function (event, arg) { 
        $scope.receiver = 'got your ' + arg;
      });
    
    }]);
    

    Plunkers

    • Regular $scope syntax (as you see above)
    • new Controller As syntax

    If you register the listener on the local $scope, it will be destroyed automatically by $destroy itself when the associated controller is removed.

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-21 22:50

    Starting angular 1.5 and it's component based development focus. The recommended way for components to interact is through the use of the 'require' property and through property bindings (input/output).

    A component would require another component (for instance the root component) and get a reference to it's controller:

    angular.module('app').component('book', {
        bindings: {},
        require: {api: '^app'},
        template: 'Product page of the book: ES6 - The Essentials',
        controller: controller
    });
    

    You can then use the methods of the root component in your child component:

    $ctrl.api.addWatchedBook('ES6 - The Essentials');
    

    This is the root component controller function:

    function addWatchedBook(bookName){
    
      booksWatched.push(bookName);
    
    }
    

    Here is a complete architectual overview: Component Communications

    0 讨论(0)
  • 2020-11-21 22:51

    Using $rootScope.$broadcast and $scope.$on for a PubSub communication.

    Also, see this post: AngularJS – Communicating Between Controllers

    0 讨论(0)
  • 2020-11-21 22:52

    This is how I do it with Factory / Services and simple dependency injection (DI).

    myApp = angular.module('myApp', [])
    
    # PeopleService holds the "data".
    angular.module('myApp').factory 'PeopleService', ()->
      [
        {name: "Jack"}
      ]
    
    # Controller where PeopleService is injected
    angular.module('myApp').controller 'PersonFormCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
      $scope.people = PeopleService
      $scope.person = {} 
    
      $scope.add = (person)->
        # Simply push some data to service
        PeopleService.push angular.copy(person)
    ]
    
    # ... and again consume it in another controller somewhere...
    angular.module('myApp').controller 'PeopleListCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
      $scope.people = PeopleService
    ]
    
    0 讨论(0)
  • 2020-11-21 22:54

    You can access this hello function anywhere in the module

    Controller one

     $scope.save = function() {
        $scope.hello();
      }
    

    second controller

      $rootScope.hello = function() {
        console.log('hello');
      }
    

    More info here

    0 讨论(0)
提交回复
热议问题