AngularJS: Sharing Data between two controllers through a service

13 / Mar / 2013 by Suroor Wijdan 2 comments

The topic of this post is quite confusing for many developers as they face problems in identifying the best practice to share data between controllers in AngularJS. Some of the articles out there tell to use $rootScope but that’s not the correct approach to enable this functionality.

A more cleaner and better way of doing so is through a shared service, lets see some code below which will make everything clear.

[js]//Angular Code
var app = angular.module(‘myApp’, []);

app.factory(‘MyTestData’, function() {
var testData = {key: ‘value’,key1:’value1′};
return {
showData: function() {
console.log(‘Printing Data…..’);
return testData;
}
};
});

function First($scope, MyTestData) {
console.log(‘First Controller………..’);
console.log(MyTestData.showData());
}

function Second($scope, MyTestData) {
console.log(‘Second Controller……….’);
console.log(MyTestData.showData());
}
[/js]

 

[html]<!–html code–></pre>
<div></div>
<div></div>
<pre>
[/html]

When you run the above code, it will console the value of testData in the browser from both the controllers. In the above code we have used .factory which is another way of defining a service, you can find more information regarding that in angular docs. I hope it helps, feel free to ask if you have any queries.

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Ashwini

    hey, you give good example , but i want to share multiple data between two or more controller with help of key and value just like hash map will you give me any hint,,,

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *