Ruben2112 Ruben2112 - 1 month ago 9
CSS Question

Change CSS of dynamic button on click

I have a couple of buttons that are dynamically placed in an ng-repeat. I want to be able to "select" a button. By that I mean when I click on one, its CSS changes. When I click another one, the first button gets its original CSS back and the new button becomes selected. Can anyone help me out?

HTML:

<button ng-repeat="answer in regular_answers" ng-attr-id="{{'answer' + answer.regularAnswerId}}" class="button button-balanced button-block" ng-click="selectAnswer(answer)">
{{answer.answer}}
</button>


JS:

$scope.selectAnswer = function (answer) {
if (document.getElementById('answer' + answer.regularAnswerId).hasClass('button-selected')) {
document.getElementById('answer' + answer.regularAnswerId).removeClass('button-selected');
document.getElementById('answer' + answer.regularAnswerId).addClass('button-balanced');
}
else {
document.getElementById('answer' + answer.regularAnswerId).removeClass('button-balanced');
document.getElementById('answer' + answer.regularAnswerId).addClass('button-selected');


}
}

Answer

When you use angular, the approach should be different, you donĀ“t change the node after an event, instead, the node should respond to data changes:

<button ng-repeat="answer in regular_answers" class="button button-block" 
  ng-click="selectAnswer(answer)" 
  ng-class = "{buttonSelected:answer.regularAnswerId == selectedAnswer.regularAnswerId, 
             buttonBalanced: answer.regularAnswerId != selectedAnswer.regularAnswerId}">
      {{answer.answer}}
</button>

And then:

$scope.selectAnswer = function (answer) {
    $scope.selectedAnswer = answer;
}

See this example: http://codepen.io/sergio0983/pen/vyYNvy

EDIT

Added another pen with a different use case of ng-class that I think is a bit cleaner:

http://codepen.io/sergio0983/pen/VmweLP

<button ng-repeat="answer in regular_answers" 
 class="button button-block" 
 ng-click="selectAnswer(answer)" 
 ng-class = "answer.regularAnswerId == selectedAnswer.regularAnswerId ? 'button-selected' : 'button-balanced'">