angularjs - Angular services -
i trying share id between controllers in angular
i have created service follows:
app.factory("idservice", function() { var id; addid = function(id) { id = id; }; getid = function() { return id; }; });
in controller trying use service follows:
app.controller('photoformcontroller', ['$scope', '$http', 'idservice' , function($scope, $http, idservice) { $scope.id = idservice.getid(); }]);
i getting error of can't call method of undefined, injecting service incorrectly. can ?
edit:
based on solution below, service no longer generates errors, unable id varaible back, can see gets set 1 controller, 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 return : " + id); return id; }; return { addid: addid, getid: getid }; });
you need return object inside factory
. returned object service instance:
app.factory("idservice", function() { var _id; //use _id instead avoid shadowing variable same name id var addid = function(id) { //use var avoid creating property on global object _id = id; }; var getid = function() { //use var avoid creating property on global object return _id; }; return { addid : addid , getid : getid }; });
Comments
Post a Comment