Working with $scope.$emit and $scope.$on

前端 未结 12 1240
花落未央
花落未央 2020-11-21 15:22

How can I send my $scope object from one controller to another using .$emit and .$on methods?

function firstCtrl($scop         


        
12条回答
  •  无人共我
    2020-11-21 15:31

    You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit or $broadcast to inform other controllers about it. In my case, I had to make http calls through my service, so I did something like this :

    function ParentController($scope, testService) {
        testService.getList()
            .then(function(data) {
                $scope.list = testService.list;
            })
            .finally(function() {
                $scope.$emit('listFetched');
            })
    
    
        function ChildController($scope, testService) {
            $scope.$on('listFetched', function(event, data) {
                // use the data accordingly
            })
        }
    

    and my service looks like this

        app.service('testService', ['$http', function($http) {
    
            this.list = [];
    
            this.getList = function() {
                return $http.get(someUrl)
                    .then(function(response) {
                        if (typeof response.data === 'object') {
                            list = response.data.results;
    
                            return response.data;
                        } else {
                            // invalid response
                            return $q.reject(response.data);
                        }
    
                    }, function(response) {
                        // something went wrong
                        return $q.reject(response.data);
                    });
    
            }
    
        }])
    

提交回复
热议问题