2014-03-27 27 views
5

這似乎不適合我。我在tr上有ng-repeatng-clickng-class。點擊tr應該切換到.errorng-repeat的切換錶行ng-class

目前點擊tr將改變類中的所有錶行。

<!doctype html> 
<html lang="en" ng-app="studentApp"> 
<head> 
    <meta charset="UTF-8"> 
    <style> 
     .is-grey-true { background-color: #ccc; } 
     .error { background-color: red; } 
    </style> 
    <script type="text/javascript" src="js/angular.min.js"></script> 
</head> 

<body ng-controller="StudentController"> 

    <table ng-hide="showTable"> 
     <tr ng-repeat="student in students" ng-class="{error : isGrey}" ng-click="toggleClass()"> 
      <td>{{student.id}}</td> 
      <td>{{student.firstname}}</td> 
      <td>{{student.lastname}}</td> 
     </tr> 
    </table> 
<script type="text/javascript"> 
    var studentApp = angular.module('studentApp',[]); 

    studentApp.controller('StudentController', function($scope){ 
     var students = [ 
      { id:1, firstname: 'Mahesh', lastname: 'Sapkal'}, 
      { id:2, firstname: 'Hardik', lastname: 'Joshi'}, 
      { id:3, firstname: 'Sagar', lastname: 'Mhatre'} 
     ]; 
     $scope.isGrey = false; 

     $scope.toggleClass = function() { 
      $scope.isGrey = true; 
     }; 
    }); 
</script> 
</body> 
</html> 

JSFiddle

+0

請問你能把小提琴嗎? –

+0

@John:加入jsfiddle。 –

+0

http://jsfiddle.net/hGE27/繼承人工作小提琴 –

回答

13

每個指同一納克級($ scope.error)。你可以定義一個包含每一行的類的數組。

$scope.isGrey = []; 

參考特定的類像這樣的HTML

<tr ng-repeat="student in students" ng-class="isGrey[$index]" ng-click="toggleClass()"> 

,改變toggleClass以下

$scope.toggleClass = function (id) { 
    $scope.isGrey[id] = $scope.isGrey[id]=='error'?'':'error'; 
}; 

http://jsfiddle.net/hGE27/

+0

工作小提琴添加 –

+0

真棒,這就是我所需要的。 .. 謝謝。 –

0

你需要翻轉isGrey的價值:

$scope.toggleClass = function() { 
    $scope.isGrey = !$scope.isGrey; 
}; 
0

,這是因爲各行建模成isGrey的相同實例。

你需要做的是聯營每一行都有自己的isGrey值。

這意味着你需要一個叫做isGrey新的屬性來更新students對象如下:

$scope.students = [ 
     { id:1, firstname: 'Mahesh', lastname: 'Sapkal', isGrey: false}, 
     { id:2, firstname: 'Hardik', lastname: 'Joshi', isGrey: false}, 
     { id:3, firstname: 'Sagar', lastname: 'Mhatre', isGrey: false} 
    ]; 

您可以將更新tr標籤爲:

<tr ng-repeat="student in students" ng-class="{error : student.isGrey}" 
    ng-click="toggleClass(student)"> 

和代碼對於toggleClass()功能爲:

$scope.toggleClass = function (student) { 
    for (var i = 0; i < $scope.students.length; i++) { 
     if ($scope.students[i].id === student.id) { 
      $scope.students[i].isGrey = true; 

      break; 
     } 
    } 
}; 
+0

是的,這樣做的一種方式,但我不想在學生對象上有一個額外的屬性。 :) –

0

正如其他人所說,$ scope.isGrey的價值確實需要根據您的必要業務規則進行切換或設置。

話雖這麼說,根據你所描述你要單獨在您需要isGrey添加到每個元素withing陣列,並且切換其值外殼顏色的每一行。

$scope.toggleClass = function(student){ student.isGrey = !student.isGrey; } 

,並在您的標記

<tr ng-repeat="student in students" ng-class="{error : student.isGrey}" ng-click="toggleClass(student)"> 

我希望這可以幫助你。

+0

我不確定他是否想爲他的學生提供這樣的房產對象。 –

+0

是的,沒錯,我不想在學生對象上增加一個屬性。 :) –