Reputation: 131
i have a problem with angularJS factory and controller i want to get the http reply in a factory and use the api reply in controller but i dont know how to handle the factory and inject it in controller
.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.
});
})
Upvotes: 1
Views: 109
Reputation: 1350
I am not exactly sure what you are looking for, but you can always return a promise by returning the http call. then grab that promise in controller and do something with it:
for example: 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);
and in your controller just inject the service:
(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);
Optional (app.js):
var _app = _app || {};
(function() {
"use strict";
_app = angular.module("myApp", []);
})();
Upvotes: 2