Change css class of an item already rendered by ng-repeat

1

I need a help with AngularJs (1.6), I need to change the css class of just one or more items already rendered by ng-repeat .

I have seen in some places that clicking the item you can send your $ index and thus change the class only of that element, which would help me, however I need this controller , without passing the $ index through the view.

I know what $ index needs to change, I just need to know how to change it after rendering without passing anything by the view.

Example, I have this and I want to change the class dynamically of the 3 (or 4, 5) item already rendered.

<ul ng-repeat="item in itens">
    <li>{{item.item}}</li>
    <li>{{item.alterarClasseDesseItem}}</li>
</ul>
    
asked by anonymous 21.03.2018 / 04:20

1 answer

3

You have some possible solutions:

EXAMPLE 1 :
One way to use the "angular way" would be to use ng-class and change it dynamically, like this:

<li ng-class='classeDinamica' id='li-1'>{{item.item}}</li>

and controller :

$scope.classeDinamica= 'nome-da-classe';

But this will change all the elements with classeDinamica , and from what I saw this is not what you want.

EXAMPLE 2
For a particular element, you can use a selector, which is not very "angular", but it works:

angular.element(document.querySelector('#li-1')).addClass('nome-da-classe')

EXAMPLE 3
Another more elegant solution in the "angular way" is to use a logical expression with ng-class using the element or the object itself that has been binding , in its example item :

<li ng-class="{'nome-da-classe': item.selecionado == true}" >{{item.item}}</li>

$scope.itens[x].selecionado = true;

This will apply to the class when the selected attribute of the item is equal to true .

EXAMPLE 4
Finally, if it is only one item selected in several, and as you said it has $index , you can create a value in $scope to save the selected element, based on $index and do as in the previous element of a% conditional%, like this:

<li ng-class="{'nome-da-classe': $index == itemSelecionado}" >{{item.item}}</li>

and finally controller :

$scope.itemSelecionado= $index;

Some of these solutions should help you

    
21.03.2018 / 12:22