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.

Chris
  • 225
  • 1
  • 5
  • 14
  • possible duplicate of [Can one controller call another in AngularJS?](http://stackoverflow.com/questions/9293423/can-one-controller-call-another-in-angularjs) – Stewie Jan 16 '14 at 06:24

1 Answers1

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 .

Zorba
  • 556
  • 5
  • 9