我有Service
和Controller
。控制器调用getItems()
上的函数Service
。 Service
会返回array
个数据。
然而,奇怪的是,控制器似乎没有收到这个。
控制器:
ItemModule.controller('ItemController', ['$scope', 'ItemService',
function ($scope, ItemService) {
$scope.items = [];
$scope.getItems = function() {
$scope.items = ItemService.getItems();
}
$scope.getItems();
}
]);
服务:
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
this.getItems = function() {
$http.get($rootScope.root + '/products').success(function(data) {
// This prints it out fine to the console
console.log(data);
return data;
});
}
}
]);
我做错了什么?
答案 0 :(得分:0)
快速且脏修复就是这样:
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
return {
getItems : function(scope) {
$http.get($rootScope.root + '/products').success(function(data) {
scope.items = data;
});
}
}
}
]);
然后在您的控制器中调用:
ItemService.getItems($scope);
但是如果您的控制器是路线的一部分(可能是),那么使用resolve
(看here)会更好。