I recently stumbled upon a helpful tutorial that taught me how to create a simple image slider using AngularJS. While I managed to implement it successfully in my project, there is one particular issue that has left me stumped.
The tutorial demonstrates hardcoding the image sources into the $scope
using $scope.slides
defined in app.js
. However, this approach doesn't suit my needs as I plan to have multiple sliders dynamically populated based on JSON data.
The challenge I'm facing revolves around the next/previous functions of the slider, which require knowing the total count of images within the slider. The tutorial achieves this with $scope.slides.length
. While hardcoding the number of images works flawlessly, I'm keen to discover a way to dynamically generate this count based on the populated slides.
Below is a snippet from my app.js
:
$scope.direction = 'left';
$scope.currentIndex = 0;
$scope.setCurrentSlideIndex = function (index) {
$scope.direction = (index > $scope.currentIndex) ? 'left' : 'right';
$scope.currentIndex = index;
};
$scope.isCurrentSlideIndex = function (index) {
return $scope.currentIndex === index;
};
// Remaining code for prevSlide() and nextSlide()
Here's my customized slider template:
<div class="slider">
<img ng-repeat="slide in vm.selectedProduct.images" class="slide slide-animation nonDraggableImage" ng-swipe-right="nextSlide()" ng-swipe-left="prevSlide()" ng-hide="!isCurrentSlideIndex($index)" ng-src="{{slide.source}}">
// Additional HTML markup for navigation controls
</div>
If you wish to see a functioning example of the slider with hardcoded values for $scope.slides.length
, check out this Plunker link.