2017-02-22 81 views
0

我有以下代码:AngularJS问题与HTTP GET导致

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' 
    }; 
}); 

我的浏览器控制台的回报:

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

但如果我写的$ scope.slides对象改为手动与$越来越HTTP .get应用程序正常工作。换句话说,我不能从作用域中的指令调用scope.slides对象。

怎么了?

+1

你可以发布'slider'和'carouselCtrl'的html吗? –

+0

我不太确定为什么你要在指令中定义幻灯片;既然你没有把你的幻灯片传递给指令,但检索它们,对吗? 我有一种轻微的感觉,在http呼叫解决之前,Angular已经消化了你的指令。 – Rob

回答

1

初始化页面时,scope.slides尚不存在(=它是undefined)。一旦api调用完成,它只会获得一个值。在你的指令中添加一个检查scope.slides的存在:

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