我有一个控制器和工厂定义如下。角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