Highlight a selected row in ng-repeat using ng-class

Highlight a selected row in ng-repeat using ng-class

In this tutorial we will be learning about  ng-class directive of Angular Js.
Angular Js is an MVC javascript framework that teaches HTML new things , using its two way data binding and dependency injection you write less and do more.

When working with tables or lists you will at some time come to a point when you would like to highlight the selected row of  a table or an item on a list.

View demohere
Download Codehere

Here I’m going to show you how to achieve it in Angular Js applications by building a simple food App .In the process of building our awesome food app we will also learn about ng-repeat and ng-class built-in directives of angular js

First lets create our food controller and add items to it and display it to the UI.

foodCtrl.js
   var foodApp = angular.module('foodApp',[]);
foodApp.controller('foodCtrl',function($scope){
    $scope.foodItems = [{
        name:'Noodles',
        price:'10',
        quantity:'1'
    },
    {
        name:'Pasta',
        price:'20',
        quantity:'2'
    },
    {
        name:'Pizza',
        price:'30',
        quantity:'1'
    },
    {
        name:'Chicken tikka',
        price:'100',
        quantity:'1'
    }];
});

Below I have defined my app and controller and displayed the items in a table using ng-repeat directive of angular.

index.html
    <html>
    <head>
        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen" />
        <link href="css/bootstrap-theme.min.css" rel="stylesheet" media="screen"/>
    </head>
    <body ng-app="foodApp" ng-controller="foodCtrl">
        <table class="table table-bordered" >
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Price</th>
                <th>Quantity</th>
            </tr>
            <tr ng-repeat="item in foodItems">
                <td></td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>{{item.quantity}}</td>
            </tr>
        </table>
    <script src="js/angular.js"></script>
    <script src="js/foodCtrl.js"></script>
    </body>
</html>

You might have noticed I’ve not yet added any thing to the first column below ‘#’, here we display the position of the row in the table by using the $index variable provided by default in ng-repeat.

<td>{{$index}}</td>

Now we will add conditional class to highlight the last clicked row by using built in ng-class directive
Add this code to the ng-repeat line – ng-class=”{‘selected’:$index == selectedRow}”

       <tr ng-repeat="item in foodItems" ng-class="{'selected':$index == selectedRow}">
           ........
       </tr>

In the above line, class “.selected” will be applied to the element if the corresponding argument “$index == selectedRow” evaluates to true.You can also add multiple classes and arguments separated by comma.

Next we have to define a function which will set our variable selectedRow to $index of the clicked row.
Lets add that function into our foodApp controller,and call it using the ng-click directive of angular js.

   $scope.selectedRow = null;  // initialize our variable to null
  $scope.setClickedRow = function(index){  //function that sets the value of selectedRow to current index
     $scope.selectedRow = index;
  }

Add below code to the ng-repeat line in index.html
ng-click=”setClickedRow($index)”

<tr ng-repeat="item in foodItems" ng-class="{'selected':$index == selectedRow}" ng-click="setClickedRow($index)">
           ........
       </tr>

Now lets define our .selected class in index.html

<style>
.selected {
    background-color:black;
    color:white;
    font-weight:bold;
}
</style>

Related link: Add animations to selection

Now whenever you click on any row our function setClickedRow($index) will set the value of selectedRow to the index of the row clicked,thus the ng-class argument for that row will evaluate to true and the .selected class will be applied for that row.

Like our articles? Get them straight to your inbox!

* indicates required
Highlight a selected row in ng-repeat using ng-class
Tagged on:                         

31 thoughts on “Highlight a selected row in ng-repeat using ng-class

  • February 13, 2015 at 9:34 pm
    Permalink

    Great post!
    You can change your setClickedRow function to remove the class if the row is clicked again:

    $scope.selectedRow = null;
    $scope.setClickedRow = function (index) {
    $scope.selectedRow = ($scope.selectedRow == index) ? null : index;
    }

    Reply
      • December 1, 2015 at 7:16 pm
        Permalink

        In the html you could shorten it even more so you don’t even need a method that sets the active index.

        ng-click=” $scope.active = $index ”

        This is the same as function(index) { $scope.active = index; }

        Reply
  • August 24, 2015 at 5:11 pm
    Permalink

    Thanks for this tut. Very helpful.

    Reply
    • September 7, 2015 at 6:11 am
      Permalink

      For multiple, you can keep an array of row indexes instead of a variable, So when user clicks on a row you push that row number into that array, if the user clicks on the same row you remove the number.
      And your row highlighting logic will check if the row index exists in that array.

      Reply
      • September 24, 2015 at 5:55 pm
        Permalink

        Can you give an example of this?

        Reply
  • September 9, 2015 at 9:14 pm
    Permalink

    Hello Rahil.,,. Once again very helpful. I want to use this code with the custom filter code you posted.. Once I select a row, how do I grab a field in that row. For example, a catalog number will be in the selected row and I want to use that number. Again I am new to Angularjs and have not begun to walk yet,, only crawl.

    Reply
    • September 14, 2015 at 6:22 am
      Permalink

      You can place a function on the row, alongside ng-repeat, and pass the catalog number for that row as parameter to the function. Use ng-click to trigger he function.

      Reply
      • September 14, 2015 at 10:04 am
        Permalink

        Thank u. so much sir…….. great blog..

        Reply
  • September 14, 2015 at 9:57 am
    Permalink

    Excellent – thanks Rahil !

    Reply
  • September 18, 2015 at 8:51 pm
    Permalink

    Great post, very usefull, thanks a lot

    Reply
  • September 27, 2015 at 11:37 am
    Permalink

    Very useful article thank you so much Rahil 🙂

    Reply
      • February 8, 2016 at 12:52 pm
        Permalink

        Hey dude,
        Thanks for the post, I really enjoyed it. Quick question, what if you want to Name, Price , Quantity values also when the row is clicked instead of displaying one value for index?
        Thank you in advance!!

        Reply
        • February 10, 2016 at 5:55 am
          Permalink

          Hi phila,
          You can simply pass the ‘item’ as a second parameter along with ‘$index’ in ‘setClickedRow’ function, like ‘setClickedRow($index, item)’. Then in controller you can easly access item to get all details for the selected row.

          Reply
  • October 8, 2015 at 9:13 am
    Permalink

    Hi Rail.
    Thank you so much, your post has been really helpful for me.
    Just a question. I need to do the same for the columns… is it possible?

    Thank you so much.

    Reply
  • October 21, 2015 at 3:48 pm
    Permalink

    Does anyone know how to get the $anchorScroll working for a table. I need to get the table scroll to the selected element in the table on page load.

    Reply
  • October 28, 2015 at 11:31 am
    Permalink

    great work…:-)…..perfectly working..

    Reply
  • October 28, 2015 at 11:33 am
    Permalink

    but i am facing some issue here ,because my table contains alternate coloring property . so its not working on alternate colored table rows.

    .tableRow:nth-of-type(odd) {

    background-color:#f3f3f3;
    }

    Please help. 🙂

    Reply
  • December 30, 2015 at 5:41 am
    Permalink

    How can i select multiple rows and highligh

    Reply
  • January 8, 2016 at 6:40 pm
    Permalink

    If the table is already filled and displayed — how can I select a row programmatically? Just calling changeSelection doesn’t seem to mimic a click on that row. I guess the question really is How to invoke a click on a row via js?

    Reply
  • February 4, 2016 at 4:15 pm
    Permalink

    I tried to implement this. It works but because I have a huge set of rows , The highlight takes a lot of time to appear. I am using ng-class as below.

    {{signal.acronym}}

    I would appreciate if you can suggest a way to overcome this performance issue.

    Thanks

    Reply
    • February 4, 2016 at 4:17 pm
      Permalink

      I am sorry. The code did not post properly.

      <button ng-class="{true: 'btn btn-primary', false:' btn btn-default'}[$index==selectedIndex]" ng-init = "showSignalInfo(selectedIndex)"

      Reply
  • March 21, 2016 at 1:23 pm
    Permalink

    Hi , when i click on the row it is highlighted (as above ) and I need the row to be shown on top out of all the rows. Help me
    Thank you.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *