How do I itterate through an unordered list and manipulate the css?


#1

I have X number of list items in an unordered list.

When a user clicks on one then I want to change the css/style of that list item (e.g. make the background yellow) and also remove the css/style of any other list item they might have clicked previously.

I currently have in each list item:

<li ng-repeat="filename in files" item="filename" ng-click="clicked(filename)">
    "{{filename}}"
</li>

which calls:

$scope.clicked = function(filename){
   alert('Clicked: ' + filename);      
};

Normally I would just whip up some jQuery but I want to use the framework correctly.

So in the “clicked” function how do I iterate the unordered list and modify each item?

Thank you very much!


#2

Hey Mark!

Here’s a codepen demo that shows how to do this with angular’s ng-class. Basically you won’t do any direct CSS manipulation. Instead you define different classes for the element. Each class has a boolean - when true it will be applied.


#3

Thanks Drew! That is really great and worked perfectly the first time I tried it.

I tweaked it a bit so that nothing is selected at first and you can deselect an item.

Thanks again!