What's the correct way to communicate between

2018-12-31 02:25发布

What's the correct way to communicate between controllers?

I'm currently using a horrible fudge involving window:

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

19条回答
十年一品温如言
2楼-- · 2018-12-31 02:44

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.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 02:45

I will create a service and use notification.

  1. Create a method in the Notification Service
  2. Create a generic method to broadcast notification in Notification Service.
  3. From source controller call the notificationService.Method. I also pass the corresponding object to persist if needed.
  4. Within the method, I persist data in the notification service and call generic notify method.
  5. In destination controller I listen ($scope.on) for the broadcast event and access data from the Notification Service.

As at any point Notification Service is singleton it should be able to provide persisted data across.

Hope this helps

查看更多
十年一品温如言
4楼-- · 2018-12-31 02:47

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

查看更多
人气声优
5楼-- · 2018-12-31 02:47

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
]
查看更多
梦寄多情
6楼-- · 2018-12-31 02:50

Using get and set methods within a service you can passing messages between controllers very easily.

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

in HTML HTML you can check like this

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

<div ng-controller='SecondController'>
    {{rslt}}
</div>
查看更多
残风、尘缘若梦
7楼-- · 2018-12-31 02:51

I liked the way how $rootscope.emit was used to achieve intercommunication. I suggest the clean and performance effective solution without polluting global space.

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');
查看更多
登录 后发表回答