Search code examples
javascriptionic-frameworkion-slides

ionic1 2 sliders on same page and its events to change particular slide


I need to change slides when I press button, as I am new to Ionic I am not able to achieve it.

<div>
    <ion-slides options="options" slider="data.slider" style="border: 1px solid;text-align: center">
        <ion-slide-page>
            <img src="slide1.png">
        </ion-slide-page>
        <ion-slide-page>
            <img src="slide1.png">
        </ion-slide-page>
    </ion-slides>
</div>
<ion-slides options="options" slider="data.slider" style="background: #fff">
    <ion-slide-page>
        <div class="product-listing-container">
        </div>
    </ion-slide-pag>
</ion-slides>
<div>
    <a class="button" ng-click="changeSlide(0)">Change Slide1</a>
    <a class="button" ng-click="changeSlide(1)">Change Slide2</a>
</div>

And now I need to change slides as I click on buttons as if I click on change Slide 1 button then slide 1 should change and same for slide 2 as well.

Can anyone help me to sort out the issue?

Thanks in advance :)


Solution

  • You can do it in this way. In your controller:

    $scope.$on('$ionicSlides.sliderInitialized', function(event, data){
        $scope.slider = data.slider;
    });
    
    $scope.changeSlide = function(slideIndex){
        $scope.slider.slideto(slideIndex);
    };
    
    $scope.prevSlide = function(){
        $scope.slider.slidePrev();
    };
    
    $scope.nextSlide = function(){
        // you can check some condition if you need to
        // if ($scope.slider.activeIndex === 1){ ... }
        $scope.slider.slideNext();
    };
    

    In your template:

    <ion-slides  options="options" slider="slider">
    (...)
    <a class="button" ng-click="prevSlide()">Previous slide</a>
    <a class="button" ng-click="changeSlide(0)">Change Slide1</a>
    <a class="button" ng-click="nextSlide()">Next slide</a>
    

    https://ionicframework.com/docs/v1/api/directive/ionSlides/

    If you have more than one slider like in your case, then you have to assign a delegate-handle to each of them:

    <ion-slides options="options" delegate-handle="slider1" style="border: 1px solid;text-align: center">
    </ion-slides>
    ... 
    <ion-slides options="options" delegate-handle="slider2" style="border: 1px solid;text-align: center">
    </ion-slides>
    

    Inject $ionicSlideBoxDelegate in your controller, and get the handle to each of the sliders:

    $scope.slider1 = $ionicSlideBoxDelegate.$getByHandle('slider1');
    $scope.slider2 = $ionicSlideBoxDelegate.$getByHandle('slider2');
    

    And use it then in the methods (note that the $ionicSlideBoxDelegate methods are differents):

    $scope.nextSlide = function(){
        $scope.slider1.next();
    };
    

    codepen example with multiple sliders