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

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

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

当前回答

在服务中使用get和set方法,可以很容易地在控制器之间传递消息。

var myApp = angular.module("myApp",[]);

myApp.factory('myFactoryService',function(){


    var data="";

    return{
        setData:function(str){
            data = str;
        },

        getData:function(){
            return data;
        }
    }


})


myApp.controller('FirstController',function($scope,myFactoryService){
    myFactoryService.setData("Im am set in first controller");
});



myApp.controller('SecondController',function($scope,myFactoryService){
    $scope.rslt = myFactoryService.getData();
});

在HTML中,你可以这样检查

<div ng-controller='FirstController'>  
</div>

<div ng-controller='SecondController'>
    {{rslt}}
</div>

其他回答

这就是我使用工厂/服务和简单依赖注入(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
]

使用rootScope美元。$broadcast和$scope。$on PubSub通信。

另外,请参阅这篇文章:AngularJS -控制器之间的通信

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

还有他们的服务图表:

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

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

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

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

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

参考:Angular Docs链接在这里