LucaP
LucaP

Reputation: 718

Angularjs scope variable in nested http get

I have a problem accessing to a scope variable defined in a nested $http.get. This is my controller code (it's related to a partial $routeProvider)

    //Content controller
app.controller('Content', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
    $http.get('wp-json/wp/v2/posts?slug=' + $routeParams.slug).success(function(res) {
        $scope.post = res[0];
        document.querySelector('title').innerHTML =  res[0].title.rendered + ' | Going Solo ';
        console.log(res);
        $http.get('wp-json/wp/v2/posts?filter[artists]=' + $scope.post.pure_taxonomies.artists[0].slug + '&exclude=' + $scope.post.id).success(function(res) {
            if (res.length > 1) {
                $scope.related = res;               
            }
            else {
                $scope.related = res[0];                
            }
            console.log(res);
        }); 
    }).error(function(res, status) {
        if (status === 404) {
            $scope.is404 = true;
            document.querySelector('title').innerHTML = 'Page not found | Going Solo';
            $scope.errorMessage = 'Error: ' + res[0].message;
        }
    });
}]);

Basically I want to retrieve all the songs related to the one that is showed in my content controller (the first $http.get). To link all the songs I use a custom taxonomy called “artists”. Of course I need this to be asynchronous so I do a new $http.get inside the first one. In this request I filter for the taxonomy slug of the current post ($scope.post.pure_taxonomies.artists[0].slug) plus I add a filter to exclude the post itself by adding its ID. This is working correctly by looking at the console log. It returns an array(1) for the first request and an array(2) for the second requests (with the correct data).

The problem is by the time I try to access in my partials to the second $http.get. If I try this ng-repeat:

<div ng-repeat="songrel in related">
    <div ng-bind-html="songrel.title.extended"></div>
</div>

Nothing is showed. It simple doesn't enter in this cycle, so I guess he doesn't recognize data.related. What am I missing?

Upvotes: 0

Views: 74

Answers (1)

ruedamanuel
ruedamanuel

Reputation: 1930

It can't find data.related because there's no $scope.data variable declared. Try just related, i.e.

<div ng-repeat="songrel in related">
    <div ng-bind-html="songrel.title.extended"></div>
</div>

Upvotes: 1

Related Questions