3

I am trying to return a JSON object in my AngularJS application. I have a list of links, I have to pass them one by one, append them to an iniatal link and then grab the json file and display it.

So far even trying with one link doesn't display any result.

This is my controller:

(function () {
    'use strict';
    angular.module('index')
        .filter('resolve', function () {
                return function (x, $http) {
                    $http.get('http://FirstPartOfTheUrl.com' + x)
                        .success(function (data) {
                            return data;
                        })
                        .error(function () {
                            return 'Error Message';
                        });
                }
            }
        })
.controller('indexController', function ($scope, $http) {
    $scope.test = 'https://theUrlIHaveToAppend.com'
})();

and this is in my HTML

<div ng-controller="indexController">
    {{test | resolve}}
</div>

displaying the page just returns {{test | resolve}}

bare in mind if i try just to print the appended url it does display the correct url and if I click on that I can actually get the file. I tried AJAX and asynchronous functions but the problem remains.

as for the recursion I will apply an ng-repeat in the div but I need this to work first.

Thanks

sinsuren
  • 1,745
  • 2
  • 23
  • 26
3ch0
  • 33
  • 4
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Jul 29 '16 at 09:26
  • Read the article and tried, doesn't solve the issue and it's not strictly related to what I am doing. I think that my problem should be easier than that – 3ch0 Jul 29 '16 at 09:52

1 Answers1

0

First of all returning from callback makes no sense

$http
   .get('http://FirstPartOfTheUrl.com'+x)
   .success(function(data) {
       return data; // this makes no sense.
   });

Then your problem is actually much harder than that. Since you need to hack into angular filter infrastructure to make it work with async code.

It would be way easier to resolve in controller

controller('indexController', function ($scope, $http) {
   $http
       .get(url)
       .then(function(data){
          $scope.test = data
       });
})

But if you really need to implement this resolving feature as filters I do recommend you to use asyncFilter from this package https://github.com/cvuorinen/angular1-async-filter The code is too complex to reproduce it here. But general idea is to use $stateful filters that recalculates on every loop.

Make your resolve filter to return a promise

.filter('resolve', function($http) {
    return function(x) {
        return $http
           .get('http://FirstPartOfTheUrl.com'+x);
   }
})

And pipe it to async filter.

{{test | resolve | async}}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98