Ian OctoBear Ian OctoBear - 1 year ago 60
AngularJS Question

Sharing data stored in angularjs

I'm trying to shared data between controller.
I'm calling data, then stored in AngularJS Factory variable.
My goal when stored the data was to make it accessible to any controller. But in application, every time i called the stored data from each controller, seems like i got a new instance of my factory instead of my factory that already contain the data.

Do you think i'm doing the wrong way when using factory or there was something i've been missed ?

Here it is

Factory Code:

var Credentials = ['abc'];
function load() {
var service = HeaderService.get("api/CredentialsAPI/get");
service.then(function (response) {
if (response.status == 200)
Credentials = response.data;
alert("inside:" + Credentials.length);
return {

SubmitCredentials : function (obj) {
angular.forEach(obj, function (value) {

GetCredentials : function (name) {
var datax = {};
angular.forEach(Credentials, function (value) {
if (value.Name == name) {
datax = value;
return datax;

Home Controller:

function loadHome() {

$scope.Credentials = CredentialsService.GetCredentials("Task");


$scope.showSubmitView = false;


$scope.Credentials[] = CredentialsService.GetCredentials("Task");

Answer Source

You're referencing a new array every time. That's why you're getting new data. You should be referencing the service instead, and have the service take care of the push() and get for you.

Factories and Services are singletons... Meaning they're only instantiated once. The pattern to share data is below:


app.factory('CredentialService',["$http", function($http) {
    var credentials = [];

    var submitCredentials = function(obj) {
        angular.forEach(obj, function(value) {

    var getCredentials = function(name) {
        var datax = {};

        if(credentials.length === 0)
            return datax;

        angular.forEach(credentials, function(value) {
            if(value.Name === name) {
                datax = value;
                break; //i think you meant to break; over here

        return datax;

    //return the service;
    return {
        getCredentials: getCredentials,
        submitCredentials: submitCredentials


app.controller("Ctrl1", ["$scope", "CredentialService", function($scope, CredentialService) {   
    var credObj = CredentialService.getCredentials('blahblahblah');

    var someNewCredObj = 'blahhhh';