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

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

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

当前回答

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

其他回答

实际上,我已经开始使用post .js作为控制器之间的消息总线。

它作为消息总线有很多好处,比如AMQP风格的绑定,邮政可以集成w/ iFrames和web套接字,以及更多的东西。

我使用装饰器在$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;
    }]);
});

这里有一个关于这个话题的博客文章的链接。 http://jonathancreamer.com/an-angular-event-bus-with-postal-js/

在服务中使用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>

我喜欢$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');

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

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

参考:Angular Docs链接在这里

我将创建一个服务并使用通知。

在Notification Service中创建一个方法 在“通知服务”中创建用于广播通知的通用方法。 从源控制器调用notificationService.Method。如果需要,我还将相应的对象传递给持久化。 在该方法中,我将数据持久化到通知服务中并调用通用notify方法。 在目标控制器中,我监听($scope.on)广播事件并从通知服务访问数据。

在任何情况下,notificationservice都是单例的,它应该能够跨跨提供持久数据。

希望这能有所帮助