Sunil Thakur
Sunil Thakur

Reputation: 97

ng-class behavior not clear

I was executing the below code (from "AngularJS" by Brad Green & Shyam Seshadri-O'Reilly). The below code sets background color as "Red", for the selected row in the table, as well as removes the background color from the previously selected row. For example, if i click on row #1 its background will be set to "red", then if i click on row #2, it's background will be set to "red" as well as background color of row #1 becomes normal (ie. it's not red now).

I am not clear on the fact that even though I have not written code to re-set the background color of other rows, how it's being reset ?

    <!-- View/Html -->
    .selected {
        background-color: red;
        }

    <table ng-controller="DynamicStyleCtrl">
        <tr ng-repeat='resturant in directory' ng-click='selectResturant($index)'
            ng-class='{selected: $index==selectedRow}'>
            <td>{{resturant.name}}</td>
            <td>{{resturant.cuisine}}</td>
        </tr>
    </table>

      <!-- Controller -->
      function DynamicStyleCtrl($scope) {
         $scope.directory = [
                        {name:'The Handsome Heifer', cusine:'BBQ'},
                        {name:'Greens', cusine:'Salads'},
                        {name:'Fine Fish', cusine:'Sea food'}
                      ];
             $scope.selectResturant = function(row){
             $scope.selectedRow=row;
           }
         }

Upvotes: 2

Views: 490

Answers (1)

link
link

Reputation: 2510

The following code will apply the class 'selected' when $index === selected row

ng-class='{selected: $index==selectedRow}'

So, when the row is selected (via ng-click) the row will have the class 'selected' which will set the background-color to red because of the css below:

.selected {
  background-color: red;
}

When the row is not selected because another row is selected, the 'selected' class that was applied via ng-class will be removed and the corresponding css will no longer be applied, therefore it will no longer be red.

Hope this helps.

Upvotes: 4

Related Questions