我有以下代码:
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'
};
});
我的浏览器控制台返回:
错误:范围。 。
但是,如果我编写$ scope.slides对象,而不是使用$ http。获得正确的工作。换句话说,我无法称呼范围。
怎么了?
初始化页面时,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;
});