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

Asked

Viewed 471 times

1

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

I saw in some places that by clicking on the item it is possible to send your $index and so change the class only of that element, which would help me, but I need this to be changed by controller, without passing the $index through the view.

I know which $index needs to change, I just need to know how to change it after rendered without going through the view.

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

<ul ng-repeat="item in itens">
    <li>{{item.item}}</li>
    <li>{{item.alterarClasseDesseItem}}</li>
</ul>

1 answer

3


There are some possible solutions:

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

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

and in the controller:

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

But this will alter all elements with classeDinamica, and from what I’ve seen that’s not what you want.

EXAMPLE 2
For a particular element, you can use a selector, which is not much the "angular way", 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 Binding, in his case item:

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

and in the controller, since you know which element (I used the index x):

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

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

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

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

and finally in controller:

$scope.itemSelecionado= $index;

Any of these solutions should help you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.