Chandana Chandana - 6 months ago 31
jQuery Question

Angularjs Change css on toggle click

I am trying to change css for table tr on click on row and unclick row.
Being a newbee to angular, I am looking for some pointer to work on it.

My fiddle started as

<div ng-controller="MyCtrl">
Hello, {{name}}!
<table border=1 width=100%>
<tr ng-click="changeBackgroundOnToggle();"><td>Test Row 1</td></tr>
<tr ng-click="changeBackgroundOnToggle();"><td>Test Row 2</td></tr>
<tr ng-click="changeBackgroundOnToggle();"><td>Test Row 2</td></tr>

</table>
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.name = 'Superhero';

$scope.changeBackgroundOnToggle= function(){
$(this).addClass(trBg);
}
}

SSH SSH
Answer

try like this.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.items = [{"name":"ali"},{"name":"reza"},{"name":"amir"}]
    $scope.changeBackgroundOnToggle= function(item){
       $scope.index = $scope.items.indexOf(item);
    }
}
.trBg{
  background-color:gray;
  color:#fff;
  font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  Hello, {{name}}!
  <table border=1 width=100%>
  <tr ng-repeat="item in items" ng-click="changeBackgroundOnToggle(item);" ng-class="{'trBg':index == $index}"><td>{{item.name}}</td></tr>
 
  </table>
</div>