Reputation: 2175
I am developing angularjs application. I have one javascript function to fill dropdown. I am making http call to get data from api. I have factory to return data. Below is code.
function fillperiod(fillperiodService) {
fillperiodService.getData().then(function(res) {
$scope.cal = response.data.data.Period;
});
}
myapp.factory('fillperiodService', ['$http', '$cookieStore', 'cfg', '$q', function($http, $cookieStore, cfg, $q) {
var baseurl = cfg.Baseurl;
var urlapi = baseurl + "api/Vehicle/GetEMIPeriod";
return {
getData: function() {
var q = $q.defer();
$http.get(urlapi).then(function(response) {
q.resolve(response);
}, function(error) {
q.reject();
})
return q.promise;
}
}
}]);
Above code throws error:
Cannot read property 'getData' of undefined.
I have declared method getData. I am not sure what i am missing in the above code. May i get some help to fix this issue? Any help would be appreciated. Thank you.
Upvotes: 0
Views: 121
Reputation: 3651
The injection mechanisms within AngularJS only work for creating things that AngularJS understands (controllers, services, filters, ...). From the looks of it, you have just a stand alone function, which isn't injected by AngularJS.
I would expect a solution that looks closer to the following would work:
myapp.controller('FillPeriodController', ['$scope', 'fillperiodService',
function($scope, fillperiodService) {
$scope.fillperiod = fillperiod;
function fillperiod() {
fillperiodService.getData().then(function(res) {
$scope.cal = response.data.data.Period;
});
}
}]);
Upvotes: 1
Reputation: 11
To answer this question we need to know the context from where you are invoking this function. In that context you should check if this factory is injected.
Upvotes: 0
Reputation: 1348
It seems like the factory is not injected into your controller. Hence, Inside your function, fillperiodService is undefined. Inject the factory into the controller from which you want to call one of its methods. then it will work.
EDIT :
myapp.controller('fillPeriod', ['fillperiodService', function(fillperiodService){
//here you can call your fillpersiodService.methodName
}])
Upvotes: 2