控制器之间的正确通信方式是什么?

我目前正在使用一个可怕的软糖涉及窗口:

function StockSubgroupCtrl($scope, $http) {
    $scope.subgroups = [];
    $scope.handleSubgroupsLoaded = function(data, status) {
        $scope.subgroups = data;
    }
    $scope.fetch = function(prod_grp) {
        $http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
    }
    window.fetchStockSubgroups = $scope.fetch;
}

function StockGroupCtrl($scope, $http) {
    ...
    $scope.select = function(prod_grp) {
        $scope.selectedGroup = prod_grp;
        window.fetchStockSubgroups(prod_grp);
    }
}

当前回答

你可以在模块的任何地方访问这个hello函数

控制器的一个

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

第二个控制器

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

更多信息请点击这里

其他回答

我喜欢$rootscope。使用Emit实现相互通信。我建议清洁和性能有效的解决方案,不污染全球空间。

module.factory("eventBus",function (){
    var obj = {};
    obj.handlers = {};
    obj.registerEvent = function (eventName,handler){
        if(typeof this.handlers[eventName] == 'undefined'){
        this.handlers[eventName] = [];  
    }       
    this.handlers[eventName].push(handler);
    }
    obj.fireEvent = function (eventName,objData){
       if(this.handlers[eventName]){
           for(var i=0;i<this.handlers[eventName].length;i++){
                this.handlers[eventName][i](objData);
           }

       }
    }
    return obj;
})

//Usage:

//In controller 1 write:
eventBus.registerEvent('fakeEvent',handler)
function handler(data){
      alert(data);
}

//In controller 2 write:
eventBus.fireEvent('fakeEvent','fakeData');

你应该使用服务,因为$rootscope是整个应用程序的访问,它会增加负载,或者如果你的数据不多,你可以使用rootparams。

关于原始代码——看起来您想要在作用域之间共享数据。要在$scope之间共享数据或状态,文档建议使用服务:

要运行跨控制器共享的无状态或有状态代码-使用 而是Angular服务。 实例化或管理的生命周期 其他组件(例如,用于创建服务实例)。

参考:Angular Docs链接在这里

实际上,使用emit和broadcast效率很低,因为事件会在作用域层次结构中上下冒泡,这很容易导致复杂应用程序的性能瓶颈。

我建议使用服务。以下是我最近在我的一个项目https://gist.github.com/3384419中实现它的方法。

基本思想——将发布/事件总线注册为服务。然后在需要订阅或发布事件/主题的地方注入事件总线。

GridLinked发布了一个PubSub解决方案,看起来设计得很好。该服务可以在这里找到。

还有他们的服务图表: