Моей директивы с контроллером:AngularJS: см, не обновляя
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
Далее() вызывается каждые 1500 мс благодаря setInterval(this.Next, 1500)
в функции Init(). Я могу видеть на консоли: 2, 3, 4, ... 10, 0, 1, 2 ...
Но в браузере {{gallery.currentIndex}}
не обновляется, отображается значение по умолчанию (2) (photoGallery.html строка 1)
использование [ '$ interval'] (https://docs.angularjs.org/api/ng/service/$interval) службы вместо' setInterval' –
Как @RahilWazir упоминалось, используйте '$ interval' или выполните ручной вызов '$ scope. $ apply()' в вашей функции интервалов ('this.Next'). 'setInterval' существует вне угловой области, поэтому вы не получите никакой функции автоматического обновления. – csbarnes
Спасибо, но в моем контроллере 'this' относится к элементу окна ... (я сделал' console.log (this); 'в конце Init()) – Apolo