Passing data from factory to controller

Hi, I want to pass a simple data from factory (hard-code data) to my controller. I run the code and inspect it. The factory does run but when it return, it only return an simple object itself, not everything defined before in the factory.

I.e. If I define a object data with a variable age = 13, when I return it to controller, it only see the object as the simple object, which doesn’t have anything in it (I confirmed this by watching the variable)

This is my current code:

myApp.controller ("venueCtrl", ["$scope", "$routeParams" ,'sharedInfo', function($scope, sharedInfo) {
  console.log("123");
  console.log(sharedInfo.age);
}])

myApp.factory('sharedInfo', function () {
  var data = {
    age: 13
  }
  console.log("factory");
  return data;
});

The console log will get this result:

factory
123
undefined //this is data.age

In addition, I also want to ask about how to declare a function in the factory like above. I tried this:

myApp.factory('sharedInfo', function () {
  var data = {
     age: 13
  }
  console.log("factory");
  return {
      getAge: function() {
         return data.age;
      }
  };
});

But when I try to call it in my controller

sharedInfo.getAge()

I get the error:

sharedInfo.getAge is not a function

I guess because the object return is the simple object so it doesn’t understand getAge as the function. Any help?

Hi mankinchi,

First off, your factory is returning “data” and your controller is looking for “age”. You need to do something like sharedInfo.data.age in your controller or return data.age in your factory.

Also, here is an example of how I would structure the code in your factory to be a bit more clear:

myApp.factory('sharedInfo', function () {
  var myFactory = {}

 var data = {
    age: 13
 }

  myFactory.getData = function(){
      return data
 }

 return myFactory;

});
1 Like

Hi,

I tried sharedInfo.data but it still goes undefined in the console log. I have some simple code on jsfiddle. Can you check it out?

http://jsfiddle.net/6sh6yhag/

New update: I found the problem. For some reasons, if I inject routeParams , the object is undefined. If I don’t, the problem is solve. However, I need routeParams also. Do you know how to combine those 2?

I updated your JSFiddle so that the controller is getting the right data, but for some reason it doesn’t recognize the controller, so I must be missing something there, but it should point you in the right direciton.

As for the routeParams, that shouldn’t be affecting anything, so you must be affecting something else unintentionally.

Hope that helps :slight_smile: