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

前端 未结 12 1245
花落未央
花落未央 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:41

    You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.

    app.controller('firstCtrl', function($scope, $rootScope) {        
            function firstCtrl($scope) {
            {
                $rootScope.$emit('someEvent', [1,2,3]);
            }
    }
    
    app.controller('secondCtrl', function($scope, $rootScope) {
            function secondCtrl($scope)
            {
                $rootScope.$on('someEvent', function(event, data) { console.log(data); });
            }
    }
    

    Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.

提交回复
热议问题