Search code examples
javascriptangularjsangularjs-scoperootscope

How to communicate controller with each other in AngularJS?


I'm writing a controller. This controller has to communicate with an other controller. But I don't know is it posible?

HTML:

<div data-ng-app="TestApp">
<div data-ng-controller="menuCtrl">
    <ul>
        <li> <a data-ng-click="Click()">
            Menü1</a>
        </li>
    </ul>
</div>
<div data-ng-controller="pageCtrl">
    <hr/> 
    <button data-ng-click="getText()">GetText</button>
    <br/>
    <strong data-ng-model="boldText"> {{boldText}}</strong>
</div>

JS:

var app = angular.module('TestApp', []);

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
    //???
    };
})
.controller('pageCtrl', function ($rootScope, $scope) {

    $scope.getText = function () {
        $scope.boldText = 'tst';
    };
});

I repaired sample on JSfiddle:sample


Solution

  • Using the events broadcast, we can pass the value form one controller to another

    app.controller('menuCtrl', function ($rootScope, $scope) {
        $scope.Click = function () {
            var valueToPass = "value";
            $rootScope.$broadcast('eventMenuCtrl', valueToPass);
        };
    })
    .controller('pageCtrl', function ($rootScope, $scope) {
    
        $scope.getText = function () {
            $scope.boldText = 'tst';
        };
    
        $scope.$on('eventMenuCtrl', function(event, value) {
            $scope.boldText = value;
        })
    });
    

    http://jsfiddle.net/q2yn9jqv/4/