Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular services

I am trying to share an id between controllers in angular

I have created a service as follows:

app.factory("idService", function() {
    var id;
    addId = function(id) {
        id = id;
    };
    getId = function() {
        return id;
    };    
});

In my controller I am trying to use this service as follows:

app.controller('photoFormController', ['$scope', '$http', 'idService' , function($scope,   $http, idService) {

       $scope.id = idService.getId();
}]);

I am getting an error of can't call method of undefined, obviously I am injecting the service incorrectly. Can someone help ?

EDIT:

Based on the solution below, the service no longer generates errors, however I am unable to get the id varaible back, I can see that it gets set from one controller, however it remains undefined in when retrieving :

app.factory("idService", function() {
    var id;
    addId = function(id) {
        id = id;
        console.log("added id of: " + id);
    };
    getId = function() {
        console.log("trying to return : " + id);
        return id;
    };
    return {
        addId: addId,
        getId: getId
    };
});
like image 403
avrono Avatar asked Mar 19 '23 21:03

avrono


1 Answers

You need to return an object inside factory. This returned object is your service instance:

app.factory("idService", function() {
    var _id; //use _id instead to avoid shadowing your variable with the same name id
    var addId = function(id) { //use var to avoid creating a property on the global object
        _id = id;
    }; 
    var getId = function() { //use var to avoid creating a property on the global object
        return _id;
    };    

    return {
        addId : addId ,
        getId : getId 
    };
});
like image 62
Khanh TO Avatar answered Mar 28 '23 14:03

Khanh TO