Angularjs factory data exchange

I wrote one factory to exchange data between controllers. Here's an example

.factory('sharedData', function () {
        var property = {
            title: '',
            color: ''

        return {
            getTitle: function () {
                return property.title;
            setTitle: function (title) {
                property.title = title;
            getColor: function () {
                return property.color;
            setColor: function (color) {
                property.color = color;


I am using a controller to set data to a factory with.



but when i try to call:



I am getting an empty string. I have included the service in the controller correctly. any help is appreciated.

Edit: Sorry to have missed one important information. I am setting data after successful REST call code like below.

var req =
                method: 'GET',
                url: "/titleName"
                headers: {
                    'Content-type': 'application/json'

                .success(function (response, status)

                .error(function (response, status)


The Json response looks like this:



console.log on a successful callback gives the correct answer as Name. Thanks to


source to share

1 answer


And I see that you are using the async method. So yes, you have to return the promise and decide its success.

Since the controller doesn't know if it's asynchronous or not, it just expects a value.

Therefore, while the service is fetching data, the controller is already requesting data.

and then an empty string will be sent to you.

When you return a promise, you can resolve it in your routing or in your controller.

// Plunkr is old because the data has changed on the question Hi, I've created a really small plunkr.

.controller('har', function(sharedData) {

Check your console

I used your factory and a simple controller and to me it looks like it works.

Do you have any other dependencies on it or do you use it in a different way.



All Articles