Angularjs在切换点击时更改css

时间:2016-06-01 05:43:41

标签: javascript jquery css angularjs html-table

我正在尝试在单击行并取消单击行时更改表tr的css。 作为一个角色的新手,我正在寻找一些指针来处理它。

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 个答案:

答案 0 :(得分:2)

您可以像这样使用ng-class:

<强> 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]
}

答案 1 :(得分:1)

尝试这样。

&#13;
&#13;
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);
    }
}
&#13;
.trBg{
  background-color:gray;
  color:#fff;
  font-weight:bold;
}
&#13;
<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>
&#13;
&#13;
&#13;