I know this duplicate but doesn't matches with anyone that's why I have posted this one. I have one controller and one factory. Factory is working fine and getting response in console but when i called a function of factory a error has been printed. Please check below code: Controller:
var app = angular.module('rsplApp',['ngRoute', 'ngCookies', 'ngResource', 'ngSanitize', 'ngValidate']);
app.controller('AddProjectController',['$scope', '$cookies', '$rootScope', '$location','Technologies', function ($scope, $cookies, $rootScope, $location, Technologies){
Technologies.loadTech().then(function(techRes){
$scope.choices = techRes;//console.log(techRes);
})
}])
Factory:
app.factory("Technologies",function($http){
var TechCat = {};
TechCat.loadTech = function(){
$http({
method : 'POST',
url : 'api/v1/technologies.php',
data : '', // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(response){
//console.log(response);
return response;
}).error(function(erronrmsg){
return erronrmsg;
})
}
return TechCat;
})
now when i refresh page I received this error: "Error: Technologies.loadTech(...) is undefined @ http://localhost/vk-angular/scripts/controllers/AddProjectController.js:4:4 "
var app = angular.module('rsplApp',['ngRoute', 'ngCookies', 'ngResource', 'ngSanitize', 'ngValidate']); app.controller('AddProjectController',['$scope', '$cookies', '$rootScope', '$location','Technologies', function ($scope, $cookies, $rootScope, $location, Technologies){ Technologies.loadTech().then(function(techRes){ $scope.choices = techRes;//console.log(techRes); }) }]); app.factory("Technologies",function($http){ var TechCat = {}; TechCat.loadTech = function(){ return $http({ method : 'POST', url : 'api/v1/technologies.php', data : '', // pass in data as strings headers : { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function(response){ //console.log(response); return response; }).error(function(erronrmsg){ return erronrmsg; }) }; return TechCat; });
You forgot to return the $http promise from the loadTech()
function. So, implicitly undefined
is returned. But in your controller you are using loadTech()
as if it returned a promise.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.