html - angularJS change color of cell on table (made with ng-repeat)


Keywords:html 


Question: 

I've got this code

<body>
<table border = 1>
        <tr>
            <td>Art</td>
            <td ng-repeat="x in books0" ng-click="clicked(0, x.name)">{{x.name}}</td>
        </tr>
        <tr>
            <td>Science</td>
            <td ng-repeat="x in books1" ng-click="clicked(1, x.name)">{{x.name}}</td>
        </tr>
        <tr>
            <td>Sport</td>
            <td ng-repeat="x in books2" ng-click="clicked(2, x.name)">{{x.name}}</td>
        </tr>
        <tr>
            <td>Literature</td>
            <td ng-repeat="x in books3" ng-click="clicked(3, x.name)">{{x.name}}</td>
        </tr>
    </table><br>
    <input type = "button" value = "logout" ng-click="logout()">
</body>

and I want to change the color of the cell to red if the book has been checked out using angular js. How would I go about changing the color?


1 Answer: 

You could use ng-class and refactor your function.

ng-class="{true: 'redColorClass', false:''}[x.isClicked === true]"

and in your controller

$scope.clicked = function(the_number, x) {
   x.isClicked = x.isClicked == true? false:true;
   // and the rest of your code then.
}

and change the click into your html to click(the_number, x)

so you give the whole book object to your function.

This way every time you trigger click function you toggle the attribute isClicked from true to false and the opposite. When it is true, the element gets the redColorClass which is a class you defined in your .css file, and makes whatever you like e.g. color:red

Also, your ng-repeat is not the optimal. Try to avoid many ng-repeats, maybe you could do it another way.