I want to know that can we communicate between two different controllers in AngularJS. Suppose I have Two modules,
Plunker: http://plnkr.co/edit/if0MQwlx9WHrD8XnMi2t?p=
your plunker has a very minor issue.
change this
angular.module('myApp', [])
to
angular.module('myApp', ['myNewApp'])
As @JB Nizet says, you do it the exact same way. You use a service
to communicate between two controllers.
One module needs to have the other module as a dependency. This is always a one-way dependency. I have made secondModule
a dependency of firstModule
.
As well, the value
in the service is stored in an object called data
. This is because JavaScript does not pass values by reference -- but does pass objects by reference. So this is a form of boxing
.
angular.module('firstModule', ['secondModule'])
.controller('FirstController', FirstController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default value'
}
}
angular.module('secondModule', [])
.controller('SecondController', SecondController);
SecondController.$inject = ['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="firstModule">
<div ng-controller="FirstController as vm">
First Controller in module firstModule<br>
<input type=text ng-model="vm.data.value" />
</div>
<div ng-controller="SecondController as vm">
Second Controller in module secondModule<br>
{{vm.data.value}}
</div>
</div>