0

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?

2
  • 1
    Can you post the html surrounding slider and carouselCtrl? Commented Feb 22, 2017 at 13:59
  • I'm not quite sure why you define slides in the directive; since you are not passing your slides to the directive but retrieve them, right? I have a slight feeling Angular is already digesting your directive before the http call is resolved. Commented Feb 22, 2017 at 14:00

1 Answer 1

1

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;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.