2016-06-01 80 views
0

我正在尝试更改表tr的css单击行和取消单击行。作为一个角色的新手,我正在寻找一些指针来处理它。Angularjs在切换点击更改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); 
    } 
} 

回答

1

试试这个。

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>

2

可以使用纳克级是这样的:

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