Marcelo J Forclaz
Marcelo J Forclaz

Reputation: 728

AngularJS issue with http get result

I have the following code:

app.controller('carouselCtrl', ['$scope', '$http', function($scope, $http){
    $http.get('/app/ajax/get-favs.php').then(function(response){
        $scope.slides = response.data;
    });
}]);

app.directive('slider', function($timeout) {
    return {
        restrict: 'AE',
        replace: true,
        scope: {
            slides: '='
        },
        link: function(scope, elem, attrs) {
            scope.currentIndex=0;

            [...]

            scope.$watch('currentIndex', function(){
                scope.slides.forEach(function(slide){
                    slide.visible=false;
                });
                scope.slides[scope.currentIndex].visible=true;
            });
        },
        templateUrl: '/app/includes/slider.html'
    };
});

My browser console returns:

Error: scope.slides is undefined .link/ [...] in line 55 (scope.slides.forEach....)

But if I write the $scope.slides object manually instead getting with $http.get the app works correctly. In other words, I can't call the scope.slides object from directive in scope.$watch.

What's wrong?

Upvotes: 0

Views: 32

Answers (1)

Fissio
Fissio

Reputation: 3758

When you initialize the page, scope.slides doesn't exist yet (= it's undefined). It will only get a value once the api call is complete. Add a check for the existence of scope.slides in your directive:

scope.$watch('currentIndex', function(){
  if (!scope.slides) return; // Added row
  scope.slides.forEach(function(slide){
    slide.visible=false;
  });
  scope.slides[scope.currentIndex].visible=true;
});

Upvotes: 1

Related Questions