Ionic slide box with button bar

I have an ionic slide box with 4 slides. You can switch between slides by clicking buttons on the bottom of the screen. How do I add class ‘active’ (using AngularJS) to the button when it’s corresponding slide is active?

For example, if the second slide is active I want second button to have class ‘active’. When you move to third slide (either by clicking third button or by sliding the screen), class ‘active’ is removed from second button and added to third button.

Here is my code:

menu.html

<ion-view view-title="Menu">

    <ion-content class="padding">

        <ion-slide-box on-slide-changed="activateTabs($index)">

            <ion-slide>
                <h1> Slide 1 </h1>
            </ion-slide>

            <ion-slide>
                <h1> Slide 2 </h1>
            </ion-slide>

            <ion-slide>
                <h1> Slide 3 </h1>
            </ion-slide>

            <ion-slide>
                <h1> Slide 4 </h1>
            </ion-slide>

        </ion-slide-box>

    </ion-content>

    <div class="button-bar">
        <a class="button button-stable" ng-click="slide(0)">1</a>
        <a class="button button-stable" ng-click="slide(1)">2</a>
        <a class="button button-stable" ng-click="slide(2)">3</a>
        <a class="button button-stable" ng-click="slide(3)">4</a>
    </div>

</ion-view>

MenuCtrl.js

myApp

.controller('MenuCtrl', function($scope, $stateParams, $ionicSlideBoxDelegate){

    $scope.slide = function(to) {
        $scope.current = to;
        $ionicSlideBoxDelegate.slide(to);
    }

});

Answer

You can achieve this by defining your buttons in the controller, so you can use $index to conditionally add a class to an object with ng-class.

Your code would look like this.

HTML

Add ng-repeat & ng-class in your html.

When you click on a button, $scope.current will be the same as the $index of that specific button button. Therefore ng-class will only add the class active to the clicked button.

<div class="button-bar">
    <a ng-repeat="button in buttons"
       ng-class="{'active': $index === current}"
       ng-click="slide($index)"
       class="button button-stable">{{ button.name }}</a>
</div>

Controller

Define your buttons with $scope.buttons inside your controller.

myApp

.controller('MenuCtrl', function($scope, $stateParams, $ionicSlideBoxDelegate){

    $scope.buttons = [
        { name: '1' },
        { name: '2' },
        { name: '3' },
        { name: '4' }
    ];

    $scope.slide = function(to) {
        $scope.current = to;
        $ionicSlideBoxDelegate.slide(to);
    }

});

CSS

Now you need to define a class .active in your css somewhere, since we declared it in your html with the ng-class directive (‘active’).

ng-class="{'active': $index === current}"