Simran Kaur
Simran Kaur

Reputation: 1101

apply CSS class in Ionic on selected div in ng-repeat

<ion-slide ng-repeat="category in uniqueCategories" ng-if="$index % 4 === 0">
    <div class="row" id="rowInSlider">
        <div class="col col-25" ng-if="$index < uniqueCategories.length" ng-click="CategorySelected(uniqueCategories[$index], $index)">
            <span class="img-centered img-padding imageDiv button button-icon">
                <img  class="smaller" src="img/south-indian-category-thumb.png">
             </span>
            <p class="smaller">{{uniqueCategories[$index]}}</p>
        </div>
        <div class="col col-25" ng-if="$index+1 < uniqueCategories.length" ng-click="CategorySelected(uniqueCategories[$index+1])">
            <div class="img-centered img-padding imageDiv button button-icon">
                <img class="smaller" src="img/south-indian-category-thumb.png">
            </div>
            <p class="smaller">{{uniqueCategories[$index+1]}}</p>
        </div>
</ion-slide>

How can I set the background color for selected div?

This is what I tried:

<div class="col col-25" ng-if="$index < uniqueCategories.length" ng-click="CategorySelected(uniqueCategories[$index], $index)" ng-class="{selectedCategory: selectedCategory[$index]" >

controller:

$scope.CategorySelected=function(categoryName, indexNumber){
  console.log(indexNumber)
$rootScope.readyToRender=false;
var selectedCategory={}
selectedCategory[indexNumber]=true;
}

But it does not work and I get no background color.

Upvotes: 0

Views: 310

Answers (1)

Michel
Michel

Reputation: 28289

You wrote:

ng-class="{selectedCategory: selectedCategory[$index]"

First, there is a missing curly bracket, but there is also another problem: you have to expose selectedCategory on the $scope:

$scope.CategorySelected = function (indexNumber){
    $scope.selectedCategory = {};
    $scope.selectedCategory[indexNumber] = true;
}

Then:

ng-class="{selectedCategory: selectedCategory[$index]}"

That said, what you want to achieve here is probably better done by adding a flag isSelected to the category object.

Upvotes: 1

Related Questions