Sharing Data between controllers in AngularJS
. Here I have created an AngularJS service named MyDataService as shown in the snippet below:
myApp.service('MyDataService', function () {
var Product = {
name: '',
price: ''
};
return Product;
});
Next let’s go ahead and create two different controllers using MyDataService. In the controllers, we are using the service created in the previous step. Controllers can be created as shown below:
var myApp = angular.module("myApp", ['CalService']);
myApp.controller("DataController1", ['$scope', 'MyDataService',
function ($scope, MyDataService) {
$scope.Product = MyDataService;
}]);
myApp.controller("DataController2", ['$scope', 'MyDataService',
function ($scope, MyDataService) {
$scope.Product = MyDataService;
}]);
On the view we can simply use the controllers as shown in the listing below:
<div ng-controller="DataController1">
<h2>In Controller 1h2>
<input type="text" ng-model="Product.name" /> <br/>
<input type="text" ng-model="Product.price" />
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
<hr/>
<div ng-controller="DataController2">
<h2>In Controller 2h2>
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
Now we can share the data between the controllers. As you can see, the name and price of the product is being set in the DataController1, and we are fetching the data in the DataController2.