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

前端 未结 19 2462
猫巷女王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 23:03

    Since defineProperty has browser compatibility issue, I think we can think about using a service.

    angular.module('myservice', [], function($provide) {
        $provide.factory('msgBus', ['$rootScope', function($rootScope) {
            var msgBus = {};
            msgBus.emitMsg = function(msg) {
            $rootScope.$emit(msg);
            };
            msgBus.onMsg = function(msg, scope, func) {
                var unbind = $rootScope.$on(msg, func);
                scope.$on('$destroy', unbind);
            };
            return msgBus;
        }]);
    });
    

    and use it in controller like this:

    • controller 1

      function($scope, msgBus) {
          $scope.sendmsg = function() {
              msgBus.emitMsg('somemsg')
          }
      }
      
    • controller 2

      function($scope, msgBus) {
          msgBus.onMsg('somemsg', $scope, function() {
              // your logic
          });
      }
      
    0 讨论(0)
  • 2020-11-21 23:04

    Regarding the original code - it appears you want to share data between scopes. To share either Data or State between $scope the docs suggest using a service:

    • To run stateless or stateful code shared across controllers — Use angular services instead.
    • To instantiate or manage the life-cycle of other components (for example, to create service instances).

    Ref: Angular Docs link here

    0 讨论(0)
  • 2020-11-21 23:04

    You should use the Service , because $rootscope is access from whole Application , and it increases the load, or youc use the rootparams if your data is not more.

    0 讨论(0)
  • 2020-11-21 23:06

    Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application.

    I would suggest to use a service. Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419.

    Basic idea - register a pubsub/event bus as a service. Then inject that eventbus where ever you need to subscribe or publish events/topics.

    0 讨论(0)
  • 2020-11-21 23:06
    function mySrvc() {
      var callback = function() {
    
      }
      return {
        onSaveClick: function(fn) {
          callback = fn;
        },
        fireSaveClick: function(data) {
          callback(data);
        }
      }
    }
    
    function controllerA($scope, mySrvc) {
      mySrvc.onSaveClick(function(data) {
        console.log(data)
      })
    }
    
    function controllerB($scope, mySrvc) {
      mySrvc.fireSaveClick(data);
    }
    
    0 讨论(0)
  • 2020-11-21 23:06

    You can do it by using angular events that is $emit and $broadcast. As per our knowledge this is the best, efficient and effective way.

    First we call a function from one controller.

    var myApp = angular.module('sample', []);
    myApp.controller('firstCtrl', function($scope) {
        $scope.sum = function() {
            $scope.$emit('sumTwoNumber', [1, 2]);
        };
    });
    myApp.controller('secondCtrl', function($scope) {
        $scope.$on('sumTwoNumber', function(e, data) {
            var sum = 0;
            for (var a = 0; a < data.length; a++) {
                sum = sum + data[a];
            }
            console.log('event working', sum);
    
        });
    });
    

    You can also use $rootScope in place of $scope. Use your controller accordingly.

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