To share data between controllers, first create a service that will hold your data.
var myApp = angular.module("app.demo", []); myApp.factory("Data", function(){ return { message: "Hello, World" }; });
Then you inject the factory into each controller.
myApp.controller("AppController1", ["$scope", "Data", function($scope, Data) { $scope.data = Data; }]); myApp.controller("AppController2", ["$scope", "Data", function($scope, Data) { $scope.data = Data; }]);
Then create a html page with the following markup. You can see below there is two controllers receiving the input value and each one is bind to the same factory called Data.
<html ng-app="app.demo"> <head> <title>Learn AngularJS - Sharing Data Between Controllers</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script> <script src="SharingDataDemo.js"></script> </head> <body> <div ng-controller="AppController1"> <input type="text" ng-model="data.message" /> <div>{{data.message}}</div> </div> <div ng-controller="AppController2"> <input type="text" ng-model="data.message" /> <div>{{data.message}}</div> </div> </body> </html>
This demo can be downloaded from my GitHub repository: https://github.com/csharpguy76/LearnAngularJS