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

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

    Below code shows the two sub-controllers from where the events are dispatched upwards to parent controller (rootScope)

    
    
        

    City : {{city}}

    Address : {{address}}

    var App = angular.module('App', []);
    
    // parent controller
    App.controller('parentCtrl', parentCtrl);
    
    parentCtrl.$inject = ["$scope"];
    
    function parentCtrl($scope) {
    
        $scope.$on('cityBoom', function(events, data) {
            $scope.city = data;
        });
    
        $scope.$on('addrBoom', function(events, data) {
            $scope.address = data;
        });
    }
    
    // sub controller one
    
    App.controller('subCtrlOne', subCtrlOne);
    
    subCtrlOne.$inject = ['$scope'];
    
    function subCtrlOne($scope) {
    
        $scope.getCity = function(city) {
    
            $scope.$emit('cityBoom', city);    
        }
    }
    
    // sub controller two
    
    App.controller('subCtrlTwo', subCtrlTwo);
    
    subCtrlTwo.$inject = ["$scope"];
    
    function subCtrlTwo($scope) {
    
        $scope.getAddrress = function(addr) {
    
            $scope.$emit('addrBoom', addr);   
        }
    }
    

    http://jsfiddle.net/shushanthp/zp6v0rut/

提交回复
热议问题