Change color of the clicked element (AngularJS)

0

I need to change the color of only the element that was clicked, in case I change the background color of the DIV, I have an ng-repeat, but when I click on the div, all others have the background changed.

<div class="cartoes" ng-class="{'active': isActive}" ng-click="isActive=!isActive" ng-repeat="item in vm.data.cartoes track by $index" ng-hide="vm.data.cartaoAtivo.proxy == item.proxy">
        <div class="row lista">
            <div class="col-xs-10">
                <span class="cartao">{{'MY_CARDS.PREPAID_CARD' | translate }} {{ item.number }} </span></br>
                <span class="validade">{{'MY_CARDS.CARD_EXPIRING_DATE' | translate }} {{ item.validade }} </span>
            </div>
            <div class="col-xs-3 text-center">
                <span class="ativo">{{ item.status.description }}</span>
            </div>
        </div>

I change the div color with the following statement ng-class="{'active': isActive}" ng-click="isActive=!isActive"

    
asked by anonymous 11.07.2018 / 14:18

1 answer

2

There's nothing wrong with your code, at least not with the base of it that was posted here.

Ensure that you are closing all tags , that you are using the variable isActive only within loops and that there is no other part of the code modifying the elements.

See your code working:

const fnController = function() {
  this.data = {};
  this.data.cartoes = [1, 2, 3, 4];
};

angular.module('app', []).controller('mainController', fnController);
div {
  background-color: azure;
  cursor: pointer;
}

.active {
  background-color: aqua;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app">
  <div ng-controller="mainController as vm">
    <div ng-class="{'active': isActive}" ng-repeat="item in vm.data.cartoes track by $index" ng-  ng-click="isActive=!isActive">
      Clique aqui
    </div>
  </div>
</div>

Editing to meet the need for the chameleon question

const fnController = function() {
  this.data = {};
  this.data.cartoes = [{}, {}, {}, {}];
  
  this.marcarSelecionado = function(selecionado) {
    for(const cartao of this.data.cartoes) {
      cartao.marcado = false;
    }
    
    selecionado.marcado = true;
  }
};

angular.module('app', []).controller('mainController', fnController);
div {
  background-color: azure;
  cursor: pointer;
}

.active {
  background-color: aqua;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app">
  <div ng-controller="mainController as vm">
    <div ng-repeat="item in vm.data.cartoes track by $index" ng-init="item.marcado = false" ng-click="vm.marcarSelecionado(item)" ng-class="{'active': item.marcado}">
      Clique aqui
    </div>
  </div>
</div>
    
11.07.2018 / 14:33