Angular: Ctrl 2 Ctrl using service

Demo to show communication between 2 controllers using a shared factory.

by Pratik Bhattachary

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="Ctrl_1">
  <h1>Controller 1</h1>
  <input type="text" ng-model="c1text">
  <br/> From Controller 2 - {{sharedObj.c2text}}
  <br/>
</div>

<div ng-controller="Ctrl_2">
  <h1>Controller 2</h1>
  <input type="text" ng-model="c2text">
  <br/> From Controller 1 - {{sharedObj.c1text}}
  <br/>

</div>

JavaScript

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

c2cDemoApp.factory("SharedService", function() {
  return {
    sharedObject: {
      c1text: "",
      c2text: ""
    }
  }
});

c2cDemoApp.controller("Ctrl_1", ['$scope', 'SharedService', function($scope, sharedService) {
  $scope.c1text = "Initial Text from Controller 1";
  sharedService.sharedObject.c1text = $scope.c1text;
  $scope.sharedObj = sharedService.sharedObject;
  $scope.$watch("c1text", function() {
    sharedService.sharedObject.c1text = $scope.c1text;
  })
}]);

c2cDemoApp.controller("Ctrl_2", ['$scope', 'SharedService', function($scope, sharedService) {
  $scope.c2text = "Initial Text from Controller 2";
  sharedService.sharedObject.c2text = $scope.c2text;
  $scope.sharedObj = sharedService.sharedObject;
  $scope.$watch("c2text", function() {
    sharedService.sharedObject.c2text = $scope.c2text;
  })

}]);