0

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);
    }
}

2 Answers 2

2

You can use ng-class like this:

HTML:

<div ng-controller="MyCtrl">
  Hello, {{name}}!
  <table border=1 width=100%>
  <tr ng-class="myColor[0]" ng-click="changeColor(0)"><td>Test Row 1</td></tr>
  <tr ng-class="myColor[1]" ng-click="changeColor(1)"><td>Test Row 2</td></tr>
  <tr ng-class="myColor[2]" ng-click="changeColor(2)"><td>Test Row 2</td></tr>

  </table>
</div>

JS:

$scope.changeColor= function(type){
// write your condition and give class Name in $scope.myColor[type]
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.