我对angularJS工厂和控制器有问题 我想在工厂中获取http回复并在控制器中使用api回复 但我不知道如何处理工厂并将其注入控制器
.controller('PlaylistsCtrl', function ($scope, $http) {
$http({ method: 'GET', url: "https://www.googleapis.com/blogger/v3/blogs/1309320265504420965/posts?key=***************" }).
success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
for (var i =0; i < data.items.length;i++)
{
var m,
urls = [],
str = data.items[i].content,
rex = /(https?:\/\/.*\.(?:png|jpg))/g;
while ( m = rex.exec( str ) ) {
urls.push( m[1] );
data.items[i].ImageURL = urls[0];
}
//data.items[i].ImageURL = urls[0];
}
$scope.playlists = data.items;
}).
error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or \\server returns response with an error status.
});
})
答案 0 :(得分:2)
我不确定你在寻找什么,但你总是可以通过返回http来回复一个承诺。然后在控制器中抓住这个承诺并用它做点什么:
例如: apiService.js
(function(app) {
"use strict";
app.factory("apiService", ["$http", function($http) {
var get = function(url, config) {
return $http.get(url, config);
};
var post = function(url, data, config) {
return $http.post(url, data, config);
};
var put = function(url, data, config) {
return $http.put(url, data, config);
};
var remove = function(url, config) {
return $http.delete(url, config);
};
return {
get: get,
post: post,
put: put,
remove: remove
};
}]);
})(_app);
并在您的控制器中注入服务:
(function(app) {
"use strict";
app.controller("MyCtrl", ["$scope", "apiService", function($scope, apiService) {
$scope.getData = function() {
apiService.get("/server/data").success(function(data) {
console.log(data);
}).error(function(err) {
console.log(err);
});
};
}
]);
})(_app);
可选(app.js):
var _app = _app || {};
(function() {
"use strict";
_app = angular.module("myApp", []);
})();