Reputation: 1350
So, my service is declared as follows:
var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {
Inside of that service I have these functions:
this.setTypeOfLaw = function (a) { localStorage.setItem('LawType', a) };
this.setCourthouse = function (a) { localStorage.setItem('Building', a) };
this.setDepartment = function (a) { localStorage.setItem('Dept', a) };
this.getTypeOfLaw = function () {
var LT = localStorage.getItem('LawType');
return LT;
};
this.getCourthouse = function () {
var BLDG = localStorage.getItem('Building');
return BLDG;
};
this.getDepartment = function () {
var DEPT = localStorage.getItem('Dept');
return DEPT;
};
My controller injects my service as follows:
JBenchApp.controller('CaseListCtrl', ['$scope', '$http', 'HoldState',
function ($scope, $http, HoldState) {
It is also injected in the app.js file.
If I add code to the controller that says
var a = HoldState.getDepartment();
I receive an error that states "getDepartment" is not a function. What?
Upvotes: 0
Views: 60
Reputation: 21642
My guess is that you could just return the this
object in your service code:
var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {
this.setTypeOfLaw = function (a) { localStorage.setItem('LawType', a) };
// add all your other functions and code as well
return this; // this is the service that will be injected into the controller
}
But without the full service definition, or at least full enough, it's hard to say exactly what you are doing incorrectly.
Upvotes: 0
Reputation: 11548
Services, Factories and Providers in angular in singletons and need to return their public api to be available when injected.
var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {
return {
setTypeOfLaw : function (a) { localStorage.setItem('LawType', a) },
setCourthouse : function (a) { localStorage.setItem('Building', a) },
setDepartment : function (a) { localStorage.setItem('Dept', a) },
getTypeOfLaw : function () {
var LT = localStorage.getItem('LawType');
return LT;
},
getCourthouse : function () {
var BLDG = localStorage.getItem('Building');
return BLDG;
},
getDepartment : function () {
var DEPT = localStorage.getItem('Dept');
return DEPT;
}
}
});
Upvotes: 1
Reputation: 151
Methods can be added to services as follows
var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {
return {
getDepartment : function() {
...
}
}
}
Then accessed as:
HoldState.getDepartment();
Hope this helps.
Upvotes: 1