2016-10-09 24 views
0

我有一些图像,我想循环使用上一个/下一个按钮。如何通过使用Angular的按钮点击来浏览图片?

图像应该是角度动态的。所以如果你点击其中一个按钮,它应该在控制器中的图像阵列中显示不同的图像。

这里基本上是我的尝试:

HTML -

<div> 
    <md-button ng-click="switchImage(-1)"> Prev Image </md-button> 
    <img ng-src="assets/img/{{image}}"/> 
    <md-button ng-click="switchImage(1)"> Next Image </md-button> 
</div> 

的JavaScript /角 -

// Character image selection array 
var self = this; 
self.images = ['image1.gif', 'image2.gif', 'image3.gif', 'image4.gif']; 
self.index = 0; 
$scope.image = self.images[self.index]; // Display the first image 

function switchImage(step) { 
    self.index += step; 
    $scope.image = self.images[self.index]; 
}; 

对什么是更好的方式来做到这一点有什么建议?

现在我拥有它的方式不会在单击按钮时更改图像。我确保将一个断点放入switchImage函数中,并且在单击按钮时不会进入它。

+1

这应该工作...你面临的问题是什么?至少在你到达数组的末尾之前,至少需要 –

+0

。需要验证'self.index + = step;'并相应地调整 – charlietfl

+0

@ A.B。这段代码由于某种原因不起作用。我想知道它有什么问题。如果我点击一个按钮,图像不会改变。 –

回答

0

如果你只是询问时索引大小达到0或4,那么你可以修改代码这样的边缘情况,即:

(另外,你需要注册在$scope该功能)

$scope.switchImage = function(step) { 
    self.index += step; 

    // When user keeps clicking next image and index crosses end of array 
    if (self.index == self.images.length) { 
    // reset to zero 
    self.index = 0; 
    } else if (self.index < 0) { 
    // else if user keeps clicking previous image and index goes negative 
    // reset to the last image 
    self.index = self.images.length - 1; 
    } 

    $scope.image = self.images[self.index]; 
}; 
+0

'size()'是什么? – charlietfl

+0

哎呀!意外地使用了Java的 –

+0

的'size()'@ShashankAgrawal我在问如何使图像循环工作。目前我的做法甚至没有进入switchImage功能 –

相关问题