1

I need to change the background color of an li tag when I click it.

   <ul>
       <li>
          <a ng-click="changeCategory(2)">Category 1</a>
       </li>
       <li>
          <a ng-click="changeCategory(2)">Category 2</a>
       </li>
       <li>
          <a ng-click="changeCategory(3)">Category 3</a>
       </li>
       <li>
          <a ng-click="changeCategory(4)">Category 4</a>
       </li>
   <ul>

   $scope.changeCategory = function(id){

   }

And I only need to change background color witch I click. It would be great if anyone can look into it.

vimuth
  • 5,064
  • 33
  • 79
  • 116
  • Possible duplicate of [Changing background color of a div on ng-click](http://stackoverflow.com/questions/32522270/changing-background-color-of-a-div-on-ng-click) – AndreaM16 Dec 23 '15 at 15:02
  • There is no accepted answer on that question – vimuth Dec 23 '15 at 15:21

1 Answers1

5

css

.selected {
  background-color: #eee;
}

html

<ul>
   <li ng-class="{'selected': category === 1}">
      <a ng-click="changeCategory(1)">Category 1</a>
   </li>
   <li ng-class="{'selected': category === 2}">
      <a ng-click="changeCategory(2)">Category 2</a>
   </li>
   <li ng-class="{'selected': category === 3}">
      <a ng-click="changeCategory(3)">Category 3</a>
   </li>
   <li ng-class="{'selected': category === 4}">
      <a ng-click="changeCategory(4)">Category 4</a>
   </li>
<ul>

javascript

$scope.changeCategory = function(id){
  // other stuff
  $scope.category = id;
}

note

I changed your first anchor to changeCategory(1) rather than changeCategory(2), presuming that was your intention. Also, this is crying out for an ng-repeat to satisfy the DRY principle.

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42