简体   繁体   中英

How to call a function in a controller from a different controller AngularJS

I'm looking on how to force a controller to refresh from another controller.

for that I'm using a simple test function :

function test() { alert('test'); }

I think using events is the best solution for this issue.

I used the following code :

First controller

.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$emit('testevent'); })

Second controller

.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
   $scope.$on('refreshr', function (event) {
        alert('test');
    }); })

but this is not working ! any advice ?

You can use $rootScope.$broadcast function to broadcast event to all child scopes. And then in you controller you do $scope.$on. But make sure that name of events are the same.

This should be it.

First controller

.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
        $rootScope.$broadcast('testevent'); 
})

Second controller

.controller('secondcontroller', function($rootScope,$scope, $http,$timeout) {
   $scope.$on('testevent', function (event) {
        alert('test');
    });
})

You event names are different, also broadcast on rootScope level.

.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
    $rootScope.$broadcast('testevent'); 
})

.controller('secondcontroller', function($rootScope,$scope, $http,$timeout) {
   $scope.$on('testevent', function (event) {
        alert('test');
   }) 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM