我对控制器的指示:
app.directive("photoGallery", function() {
return {
restrict: 'E',
templateUrl: 'part/photoGallery.html',
controller: ["$http", function($http) {
me = this;
this.autoSlide = true;
this.currentIndex = 2;
this.autoSlide_timer;
this.photos = [{}];
this.Show = function(index) {
me.currentIndex = index;
};
this.Next = function() {
me.currentIndex++;
console.log(me.currentIndex);
if (me.currentIndex >= me.photos.length) {
me.currentIndex = 0;
}
me.Show(me.currentIndex);
};
this.Prev = function() {
me.currentIndex--;
if (me.currentIndex < 0) {
me.currentIndex = me.photos.length-1;
}
me.Show(me.currentIndex);
};
this.Init = function() {
$http.get("img/slider/_data.json")
.success(function(data) {
me.photos = data;
for(var i in me.photos) {
me.photos[i].index = i;
}
console.info(me.photos);
})
.error(function(e){
console.error(e);
});
this.autoSlide_timer = setInterval(this.Next, 1500);
}();
}],
controllerAs: 'gallery'
};
});
photoGallery.html:
<div class="GalleryContainer">{{gallery.currentIndex}}
<div class="PhotoWrapper">
<div ng-repeat="photo in gallery.photos" class="photo" ng-class="{active:gallery.currentIndex == photo.index}">
<img ng-src="img/slider/{{photo.path}}">
</div>
</div>
</div>
如你所见,在Next()函数中,我记录currentIndex
由于Init()函数中的setInterval(this.Next, 1500)
,因此每隔1500ms调用一次Next()。
我可以在控制台中看到:2,3,4,... 10,0,1,2 ......
但是在浏览器中,{{gallery.currentIndex}}
永远不会更新,它会显示默认值(2)(photoGallery.html第1行)
答案 0 :(得分:1)
您必须使用角度$interval()
而不是JavaScript setInterval()
功能。为什么?
因为Angular需要知道何时更新变量。 $interval
在执行结束时调用$scope.$apply()
,执行新的$digest
循环,通知更新为angular。
您也可以等待请求成功继续设置间隔,以避免错误。
this.Init = function() {
$http.get("img/slider/_data.json")
.success(function(data) {
me.photos = data;
for(var i in me.photos) {
me.photos[i].index = i;
}
console.info(me.photos);
me.autoSlide_timer = $interval(me.Next, 1500);
})
.error(function(e){
console.error(e);
});
}();