我认为我的问题与$ scope有关。$ apply但我不确定在哪里放。它也可能与一般概念的理解不足有关。任何清晰度都将不胜感激。
有几个关键点,我使用了一个browserify worflow,因此我正在导出我的指令,它们在应用程序中完全正常运行。
我已经得到以下代码:
exports.gestutGallery = function() {
return {
scope: {
auto: '='
},
controller: function($scope){
$scope.galleryImages = [];
$scope.totalImages = $scope.galleryImages.length-1;
$scope.currentImageIndex = 0;
// Ternary check to set previous image
$scope.previousImageIndex =
$scope.currentImageIndex - 1 >= 0 ? $scope.currentImageIndex - 1 : $scope.totalImages;
// Ternary check to set next image
$scope.nextImageIndex =
$scope.currentImageIndex + 1 <= $scope.totalImages ? $scope.currentImageIndex + 1 : 0;
//Function References
this.addToImages = function(image, cb){
$scope.galleryImages.push(image);
};
this.pushImage = function(image){
console.log(image);
};
this.pushPreviousImage = function(){
pushImage($scope.galleryImages[$scope.previousImageIndex])
};
this.pushNextImage = function(){
pushImage($scope.galleryImages[$scope.nextImageIndex])
};
},
restrict: 'A',
link: function(scope, elem, attrs) {
console.log(scope.totalImages);
}
};
};
exports.gestutGalleryNavigation = function() {
return {
scope:true,
require: "^gestutGallery",
link: function(scope, elem, attrs, gsGlCtrl) {
var navElements = elem.children();
for(var i=0; i<navElements.length; i++){
gsGlCtrl.addToImages(navElements[i].getAttribute('data-full-size-image'));
};
}
}
};
我希望能够在将我的dom中的图像插入图像数组后更新totalImages, previousImageIndex, nextImageIndex
等的值。但它不起作用。我在哪里/如何更新这些值?我尝试过使用$ observe而没有运气,我已经尝试调用$ scope。$ apply()在循环之后但总是得到一个错误,摘要已经在进行中。
感谢您帮助解释我做错了什么。
所以,经过一些进一步的研究,我已经决定在$ watchCollection中嵌套我的$ scope.value依赖数字,如下所示:
$scope.galleryImages = [];
$scope.currentImageIndex = 0;
$scope.$watchCollection('galleryImages', function() {
$scope.totalImages = $scope.galleryImages.length-1;
// Ternary check to set previous image
$scope.previousImageIndex =
$scope.currentImageIndex - 1 <= 0 ? $scope.totalImages : $scope.currentImageIndex - 1;
// Ternary check to set next image
$scope.nextImageIndex =
$scope.currentImageIndex + 1 <= $scope.totalImages ? $scope.currentImageIndex + 1 : 0;
});
我觉得这可能比我想要的更贵,因为我认为每个图像插入都会调用$ watch函数。但是,它的工作原理和用例足够快。我将在今天剩下的时间里保持开放状态,看看是否有人可以提出更优雅的解决方案,而且更具有角度,而且我会接受自己的解决方案。答案。
答案 0 :(得分:0)
您可以将$scope.totalImages
,$scope.previousImageIndex
和$scope.nextImageIndex
更改为功能:
$scope.totalImages = function(){ return $scope.galleryImages.length; };
// Ternary check to set previous image
$scope.previousImageIndex = function(){
$scope.currentImageIndex - 1 >= 0 ? $scope.currentImageIndex - 1 : $scope.totalImages();
};
// Ternary check to set next image
$scope.nextImageIndex = function (){
$scope.currentImageIndex + 1 <= $scope.totalImages() ? $scope.currentImageIndex + 1 : 0;
};