我有以下代码:
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未定义 .link / [...]第55行(scope.slides.forEach ....)
但是,如果我手动编写$ scope.slides对象而不是使用$ http.get,则应用程序可以正常工作。换句话说,我无法从范围内的指令调用scope.slides对象。$ watch。
怎么了?
答案 0 :(得分: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;
});