Legues Legues - 8 months ago 70
AngularJS Question

Angular Service - Pass $http data to scope

I´m trying to create an angular function inside on Service to return acess data via $http and then return to a desired scope.

So my service it something like this;

app.service('agrService', function ($http) {

this.testinho = function(){
return "teste";

this.bannerSlides = function(){

var dataUrl = "data/banner-rotator.json";

// Simple GET request example :
method: 'GET',
dataType: "json",
url: dataUrl
.success( function(data, status, headers, config) {

// this callback will be called asynchronously
// when the response is available

return data;

}).error( function(data, status, headers, config) {

// called asynchronously if an error occurs
// or server returns response with an error status.
alert("Niente, Nada, Caput");



Then i want to associate the returned data to a scope inside of my main App controller... like this:

app.controller('AppCtrl', function($scope, $http, agrService) {
$scope.slides = agrService.bannerSlides();

Then in my template i want to loop the data like this:

<div ng-repeat="slide in slides">
<div class="box" style="background: url('{{ slide.url }}') no-repeat center;"></div>

The problem is that the data it´s only available on success and i don´t know how to pass it to my scope slides!!!!!

What i´m doing wrong?

Many thanks in advance

Answer Source

bannerSlides() doesn't return the values you need right away. It returns a promise that you can use to obtain the value at a later time.

In your service you can use the .then() method of the promise that $http() produces to do initial handling of the result:

 return $http({
    method: 'GET',
    dataType: "json",
    url: dataUrl
 }).then(function (data) {
     // inspect/modify the received data and pass it onward
     return data.data;
 }, function (error) {
     // inspect/modify the data and throw a new error or return data
     throw error;

and then you can do this in your controller:

app.controller('AppCtrl', function($scope, $http, agrService) {
     agrService.bannerSlides().then(function (data) {
         $scope.slides = data;