In this tutorial, we’ll delve into the ng-class directive of AngularJS, a powerful MVC JavaScript framework known for its two-way data binding and dependency injection. We’ll create a simple food application that highlights the selected row in a table or an item in a list, a common requirement when working with tables or lists. You can view the demo here and download the code here.

Creating the Food Controller

First, let’s create our food controller, add items to it, and display it in the UI. Here’s the foodCtrl.js file:

var foodApp = angular.module('foodApp',[]);
  $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'}

In this code, we’ve defined our app and controller and displayed the items in a table using the ng-repeat directive of Angular.

Displaying Items in a Table

Next, let’s display the items in a table using the ng-repeat directive. Here’s the index.html file:

<!-- Code goes here -->

In this code, we’ve used the $index variable provided by default in ng-repeat to display the position of the row in the table.

Adding Conditional Class to Highlight the Last Clicked Row

Now, let’s add a conditional class to highlight the last clicked row using the built-in ng-class directive. Add this code to the ng-repeat line: ng-class="{ 'selected': $index == selectedRow }".

In this line, the 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 a comma.

Defining a Function to Set the Selected Row

Next, let’s define a function that sets our variable selectedRow to the $index of the clicked row. Add this function to our foodApp controller and call it using the ng-click directive of AngularJS:

$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 the following code to the ng-repeat line in index.html: ng-click="setClickedRow($index)".

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

Defining the .selected Class

Finally, let’s define our .selected class in index.html:

/* CSS code goes here */

By following this tutorial, you’ve learned how to use the ng-class and ng-repeat directives in AngularJS to highlight selected rows in a table. This is a fundamental skill for creating dynamic and interactive web applications.

Similar Posts