0

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

edi9999
  • 19,701
  • 13
  • 88
  • 127
Salih KARAHAN
  • 299
  • 1
  • 4
  • 18
  • possible duplicate of [What's the correct way to communicate between controllers in AngularJS?](http://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs) – Michal Charemza Feb 11 '15 at 08:39

2 Answers2

1

You can easily achieve that with broadcasting:

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

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
        $scope.$broadcast('MyClickEvent', {
           someProp: 'Clicking data!' // send whatever you want
        });

    };
})

.controller('pageCtrl', function ($rootScope, $scope) {

   $scope.getText = function () {
       $scope.boldText = 'tst';
   };
   $scope.$on('MyClickEvent', function (event, data) {
        console.log(data); // 'Data to send'
   });
});
Ben Diamant
  • 6,186
  • 4
  • 35
  • 50
0

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/