ParentCtrl ChildCtrl communication by event

by tridip

HTML

<div ng-app ng-controller="ParentCtrl">
    <button ng-click="ShowParent()">ShowParent</button>
    
        <div ng-controller="ChildCtrl as vm">
        <button ng-click="ShowChild()">ShowChild</button>
        <br>
        <br>
           {{$parent.cities}}
           <br>
           {{vm.parentcities}}
        </div>
    </div>

JavaScript

function ParentCtrl($scope) {
        $scope.cities = ["NY", "Amsterdam", "Barcelona"];
				$scope.ShowParent = function() {
    			alert('parent');
           $scope.$broadcast('childEvent', [1,2,3]);
  			};  

				$scope.$on('parentEvent', function(event, data) { alert(data); });
    }
    
    function ChildCtrl($scope) {
        $scope.parentcities = $scope.$parent.cities;
				$scope.ShowChild = function() {
    			alert('child');
          $scope.$emit('parentEvent', [1,2,3]);
  			};    
        
        $scope.$on('childEvent', function(event, mass) 
        { 
        	alert(mass); 
        });        
    }