Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular toggle table row ng-class with ng-repeat

This seems not to be working for me. I've a ng-repeat,ng-click and ng-class on the tr. Clicking on the tr should toggle the class to .error.

Currently clicking a tr will change the class of all the table rows.

<!doctype html>
<html lang="en" ng-app="studentApp">
<head>
    <meta charset="UTF-8">
    <style>
        .is-grey-true { background-color: #ccc; }
        .error { background-color: red; }
    </style>
    <script type="text/javascript" src="js/angular.min.js"></script>
</head>

<body ng-controller="StudentController">

    <table ng-hide="showTable">
        <tr ng-repeat="student in students" ng-class="{error : isGrey}" ng-click="toggleClass()">
            <td>{{student.id}}</td>
            <td>{{student.firstname}}</td>
            <td>{{student.lastname}}</td>
        </tr>
    </table>
<script type="text/javascript">
    var studentApp = angular.module('studentApp',[]);

    studentApp.controller('StudentController', function($scope){
        var students = [
            { id:1, firstname: 'Mahesh', lastname: 'Sapkal'},
            { id:2, firstname: 'Hardik', lastname: 'Joshi'},
            { id:3, firstname: 'Sagar', lastname: 'Mhatre'}
        ];
        $scope.isGrey = false;

        $scope.toggleClass = function () {
            $scope.isGrey = true;
        };
    });
</script>
</body>
</html>

JSFiddle

like image 672
msapkal Avatar asked Mar 27 '14 11:03

msapkal


1 Answers

Every refers to the same ng-class ($scope.error). You could define an array that contais the class for every row.

$scope.isGrey = [];

Refer to the specific class like this in HTML

<tr ng-repeat="student in students" ng-class="isGrey[$index]" ng-click="toggleClass()">

and change the toggleClass to the following

$scope.toggleClass = function (id) {
    $scope.isGrey[id] = $scope.isGrey[id]=='error'?'':'error';
};

http://jsfiddle.net/hGE27/

like image 116
John Smith Avatar answered Oct 30 '22 10:10

John Smith