1

I need to have one controller in an angularjs file call a refresh on another controller in the same javascript file.

I have created a very simplified version of what I need in the following set of code. Basically when I click button 1 in the example below I want it to call the click1 function and then have the click1 function call click2 function on the 2nd controller. And then the opposite to be true when you click on the click2 function in the 2nd controller.

HTML

<div ng-app> <div ng-controller="Control1"> <div>{{count1}}</div> <button ng-click="click1()">Call both click methods from controller 1</button> </div> <div ng-controller="Control2"> <div>{{count2}}</div> <button ng-click="click2()">Call both click methods from controller 2</button> </div> </div> 

Javascript

function Control1($scope) { $scope.count1 = 0; $scope.click1 = function () { $scope.count1++; } } function Control2($scope) { $scope.count2 = 0; $scope.click2 = function () { $scope.count2 = $scope.count2 + 2; } } 

I also created a jsfiddle for this.

1

1 Answer 1

2

You are going to have to use scope broadcast or emit... Something like

function Control1($scope, $rootScope) { $scope.count1 = 0; $scope.$on('clicked2', function() { $scope.count1++; }); $scope.click1 = function () { $scope.count1++; $rootScope.$broadcast('clicked1'); } } function Control2($scope, $rootScope) { $scope.count2 = 0; $scope.$on('clicked1', function() { $scope.count2 = $scope.count2 + 2; }) $scope.click2 = function () { $scope.count2 = $scope.count2 + 2; $rootScope.$broadcast('clicked2'); } } 

http://jsfiddle.net/jX3kh/ Read more on that here http://docs.angularjs.org/api/ng.$rootScope.Scope#methods_$broadcast .

Sign up to request clarification or add additional context in comments.

1 Comment

This feels a little hacky, but it totally works. Wish I knew of a better way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.