Angular: Inter-controller comm

http://angularjs.org/

by shwon24

HTML

<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
  showDialog: {{showDialog}}
    <button  ng-click="show()">Show</button>
    

    <div ng-controller="Dialog">
        {{showDialog}}
        <button ng-click="hide()">Hide</button>
    </div>
</div>

JavaScript

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

myApp.service('messageService', ['$rootScope', function($rootScope) {

    return {
        publish: function(name, parameters) {
            $rootScope.$emit(name, parameters);
        },
        subscribe: function(name, listener) {
            $rootScope.$on(name, listener);
        }
    };}]);


myApp.controller('MyCtrl', ['$scope', 'messageService', function($scope, messageService) {
    $scope.showDialog = false;
    $scope.name = 'Superhero';

    $scope.show = function() {
        messageService.publish('dialog', {
            show: true
        });
    };

    messageService.subscribe('dialog', function(event, parameters) {
        $scope.showDialog = parameters.show;
    });

    }]);

myApp.controller('Dialog', ['$scope', 'messageService', function($scope, messageService) {

    $scope.hide = function() {
        messageService.publish('dialog', {
            show: false
        });
    };}]);