Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 49076

Passing data from factory to controller

$
0
0

@mankinchi wrote:

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?

Posts: 5

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 49076

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>