Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-ng-click

Changing class on $index selection in ng-repeat with button click


I have a list of ng-repeat items. When you click on them, a class is added which changes the look of the image. I would like to now make this happen when the left and right buttons are clicked. So you can click left to put the class on the left as left is selected, and click right button to scroll through and add the class to the right.

html:

<div class="options">
    <div ng-repeat="colour in colours" class="swatch-option" ng-class="{ chosen: $index === index }">
        <div class="swatch-title" ng-show="$index === index"><p class="text"> {{colour.thumbData.description | smcl10n}} </p></div>
        <img ng-click="changeColour($index);" ng-src="{{colour.thumbMedia | smcmediaurl}}" class="colour-swatches" />
    </div>
</div>


        <div class="arrow left small" ng-click="changeColour($index)(-1)" ng-src="{{colour.thumbMedia | smcmediaurl}}"></div>
        <div class="arrow right small" ng-click="changeColour($index)(1)" ng-src="{{colour.thumbMedia | smcmediaurl}}"></div>

js:

        $scope.index = 0;
        $scope.selected = $scope.colours[$scope.index];

        $scope.changeColour = function changeColour(_index){
            $scope.index = _index
            $scope.selected = $scope.colours[$scope.index];
        }

Solution

  • You can't access $index outside of ng-repeat scope. It will be undefined. Instead work with your controller scope variable index.

        <div class="arrow left small" ng-click="changeColour(index-1)" ng-src="{{colour.thumbMedia | smcmediaurl}}"></div>
        <div class="arrow right small" ng-click="changeColour(index+1)" ng-src="{{colour.thumbMedia | smcmediaurl}}"></div>