我有一個控制器和工廠定義如下。角js從工廠返回undefined對象
myApp.controller('ListController',
function($scope, ListFactory) {
$scope.posts = ListFactory.get();
console.log($scope.posts);
});
myApp.factory('ListFactory', function($http) {
return {
get: function() {
$http.get('http://example.com/list').then(function(response) {
if (response.data.error) {
return null;
}
else {
console.log(response.data);
return response.data;
}
});
}
};
});
什麼讓我困惑的是,我從我的控制器未定義輸出,然後控制檯輸出的下一行是我從我的工廠對象的列表。我也試圖改變我的控制器
myApp.controller('ListController',
function($scope, ListFactory) {
ListFactory.get().then(function(data) {
$scope.posts = data;
});
console.log($scope.posts);
});
但我收到錯誤
TypeError: Cannot call method 'then' of undefined
注:我發現在使用工廠通過http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html