Use angular service to communicate between 2 controller.
Watch this Video
Yes $broadcast will work for you.
Here are some essential parts:
- Create service that implements message bus functionality (e.g.
$scope
instance)
- Inject service to both controllers
$broadcast()
event from one controller
- subscribe to event with
$on()
in another
Example:
HTML
<div ng-controller="ctrl1 as ctrl1">
<button ng-click="ctrl1.hello()">Say hello</button>
</div>
<div ng-controller="ctrl2 as ctrl2">{{ctrl2.messages}}</div>
JavaScript
angular.module('app', [])
.service('messageBus', ['$rootScope', function($rootScope) {
return $rootScope.$new();
}])
.controller('ctrl1', ['messageBus', function(messageBus) {
this.hello = function() {
messageBus.$broadcast('hello', 'Hi! '); // <= send message
}
}])
.controller('ctrl2', ['messageBus', function(messageBus) {
var ctrl2 = this;
this.messages = '';
console.log(messageBus.mb)
messageBus.$on('hello', function(evt, msg) { // <= receive message
ctrl2.messages += msg;
});
}]);