1

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 ?

2
  • In the provided code, both event does not have same names ('testevent', 'refreshr' ?, both controller have same name ('firstcontroller')? Commented Jun 2, 2015 at 9:02
  • See this answer to a similar thread: stackoverflow.com/a/14502755/2509908 Commented Jun 2, 2015 at 9:03

2 Answers 2

2

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');
   }) 
})
Sign up to request clarification or add additional context in comments.

Comments

2

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');
    });
})

1 Comment

Thanks for your answer ! can you please give an example according to my code !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.