Call a method of a controller from another controller using 'scope' in AngularJS

前端 未结 3 1623
悲&欢浪女
悲&欢浪女 2020-11-29 21:31

I am trying to call a method of second controller in first controller by using scope variable. This is a method in my first controller:

$scope.i         


        
3条回答
  •  长情又很酷
    2020-11-29 22:02

    Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

    HTML

    JS

    var myModule = angular.module('myModule', []);
    
    myModule.factory('mySharedService', function($rootScope) {
        var sharedService = {};
    
        sharedService.message = '';
    
        sharedService.prepForBroadcast = function(msg) {
            this.message = msg;
            this.broadcastItem();
        };
    
        sharedService.broadcastItem = function() {
            $rootScope.$broadcast('handleBroadcast');
        };
    
        return sharedService;
    });
    

    By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

    myModule.directive('myComponent', function(mySharedService) {
        return {
            restrict: 'E',
            controller: function($scope, $attrs, mySharedService) {
                $scope.$on('handleBroadcast', function() {
                    $scope.message = 'Directive: ' + mySharedService.message;
                });
            },
            replace: true,
            template: ''
        };
    });
    

    And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

    function ControllerZero($scope, sharedService) {
        $scope.handleClick = function(msg) {
            sharedService.prepForBroadcast(msg);
        };
    
        $scope.$on('handleBroadcast', function() {
            $scope.message = sharedService.message;
        });
    }
    
    function ControllerOne($scope, sharedService) {
        $scope.$on('handleBroadcast', function() {
            $scope.message = 'ONE: ' + sharedService.message;
        });
    }
    
    function ControllerTwo($scope, sharedService) {
        $scope.$on('handleBroadcast', function() {
            $scope.message = 'TWO: ' + sharedService.message;
        });
    }
    

    The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

提交回复
热议问题