Jelle Van de Vliet
Jelle Van de Vliet

Reputation: 81

Change css class of button clicked in angular with ng-repeat

This is what I want to do:

I'm working in a laravel blade document, so I have to skip angular's double curly brackets by placing an @ in front, like this: @{{ xxx }}.

The code at the moment correctly logs the data-correct attribute. But it changes the class of all the buttons, not only the one clicked.

My code:

html:

<a href ng-click="validateClick(premier.correct, $index)"
           ng-class="{premier: isPremier, random: isRandom}"
           ng-repeat="premier in premiers"
           class="btn btn-default btn-game"
           data-correct="@{{premier.correct}}"
           href="#"
           role="button">
                @{{premier.name}}
</a>

app.js:

$scope.validateClick = function(row, index) {
    if (row == "premier") {
        $scope.isPremier = true;
        console.log($scope.isPremier + index)
    }
    else {
        $scope.isRandom = true;
        console.log($scope.isRandom + index)
    }
}

Upvotes: 2

Views: 1757

Answers (1)

Karthik Easwaran
Karthik Easwaran

Reputation: 504

Instead of assigning to the common scope variable assign it to the premier object and use it in the class

HTML

<div ng-click="validateClick(premier, $index)" ng-class="{premier: premier.isPremier, random: premier.isRandom}" ng-repeat="premier in premiers" class="btn btn-default btn-game" data-correct="{{premier.correct}}" href="#" role="button">
                {{premier.name}}
</div>

Controller

$scope.validateClick = function (premier, index) {
        if (premier.correct == "premier") {
            premier.isPremier = true;
            console.log(premier.isPremier + index)
        } else {
            premier.isRandom = true;
            console.log(premier.isRandom + index)
        }
    }

Working sample is available in the jsFiddle http://jsfiddle.net/cce2g6y2/1/

Upvotes: 2

Related Questions