Ian OctoBear Ian OctoBear - 6 months ago 8
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);
}
load();
return {

SubmitCredentials : function (obj) {
angular.forEach(obj, function (value) {
Credentials.push(value);
});
},

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


Home Controller:

loadHome();
function loadHome() {

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


AssignTask

$scope.showSubmitView = false;


//----------------------------------function--------------------------------------

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

Answer

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:

Factory

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

    var submitCredentials = function(obj) {
        angular.forEach(obj, function(value) {
            credentials.push(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
    };
}]);

Controller

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

    var someNewCredObj = 'blahhhh';
    CredentialService.submitCredentials(someNewCredObj);
}]);
Comments