这是我的工厂的样子:
myApp.factory('displayAll', function($http){
var service = {};
var aaudit = [];
service.callAudit = function () {
$http.get(AuditUrl).then(function(response) {
aaudit = response.data.SrchResults;
aaudit.splice(0,1);
console.log(aaudit)
return aaudit;
});
}
return service;
});
我正在尝试将审计信息发送给控制器,我该怎么做?因为我看到的示例都只是检索URL。有可能按照我的方式来做吗?
控制器:
var CategoryExhibit = displayAll.callExhibit()
.then(function (response) {
$scope.exhibitions = response.data.SrchResults;
$scope.exhibitions.splice(0,1);
}, function (error) {
console.log(error);
});
它以这种方式工作,但是我试图将整个代码块移入工厂,以便我也可以在其他控制器上使用它
更新:
service.callAudit = function () {
$http.get(AuditUrl).then(function(data) {
aaudit = response.data.SrchResults;
aaudit.splice(0,1);
console.log(aaudit)
return aaudit;
});
}
答案 0 :(得分:1)
您需要从服务return $http.get()
退还诺言
这是一个可行的例子
angular.module("app",[]).controller("myCtrl",function($scope, auditService){
$scope.exhibitions = {};
auditService.callAudit()
.then(function (response) {
$scope.exhibitions = response;
}, function (error) {
console.log(error);
});
}).factory('auditService', function($http){
var service = {};
var aaudit = [];
service.callAudit = function () {
return $http.get('https://jsonplaceholder.typicode.com/todos').then(function(response) {
aaudit = response.data;
console.log(aaudit.splice(0,1))
return aaudit.splice(0,1);
});
}
return service;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
{{exhibitions}}
</div>