2017-08-29 47 views
2

我使用具有可擴展行的ng-repeat創建表格。我應該可以一次擴展一個表格行。如果我展開一行,那麼先前展開的行應該關閉。 請讓我知道是否需要任何進一步的細節。謝謝。Angularjs:在使用ng-repeat創建的表格中只擴展一個表格行

Plunker

<tbody> 
    <tr ng-repeat-start="person in people"> 
    <td> 
     <button ng-if="person.expanded" ng-click="person.expanded = false">-</button> 
     <button ng-if="!person.expanded" ng-click="person.expanded = true">+</button> 
    </td> 
    <td>{{person.name}}</td> 
    <td>{{person.gender}}</td> 
    </tr> 
    <tr ng-if="person.expanded" ng-repeat-end=""> 
    <td colspan="3">{{person.details}}</td> 
    </tr> 
</tbody> 
+0

請我的示例代碼?p =預覽 –

+0

請編輯您的問題並在那裏添加您的plnkr。 –

回答

2

您可以編寫一個函數來實現這一目標。該函數將當前行作爲參數並隱藏所有其他行並僅啓用當前行。

HTML

<button ng-if="!person.expanded" ng-click="expandSelected(person)">+</button> 

JS

$scope.expandSelected=function(person){ 
    $scope.people.forEach(function(val){ 
     val.expanded=false; 
    }) 
    person.expanded=true; 

    } 

工作Plunkerhttp://plnkr.co/edit/jpMCxzAwdbZYUlRylJPN?p=preview

+0

爲此使用'.forEach'? '.map'用於將數組轉換爲另一個數組。 – Icycool

+0

我已經更新了答案。地圖將返回相同值的數組。那麼,什麼時候應該使用.map? – Vivz

+1

假設在一個接受用戶ID數組的刪除API中,可以使用'.map'將用戶數組'[{id:1,name:'a'},...]'轉換成'[1]'' – Icycool

1

根據您的要求,沒有必要去通過整個數組檢查任何其他行被打開a關閉那個。 只存儲ROWNUMBER的細節和使用,在您的TR這樣

<tr ng-repeat-start="person in people track by $index"> 
      <td> 
       <button ng-if="rowNumber == $index" ng-click="detailView(-1)">-</button> 
       <button ng-if="rowNumber != $index" ng-click="detailView($index)">+</button> 
      </td> 
      <td>{{person.name}}</td> 
      <td>{{person.gender}}</td> 
      </tr> 
      <tr ng-if="rowNumber == $index" ng-repeat-end=""> 
      <td colspan="3">{{person.details}}</td> 
      </tr> 

和一個函數來這裏http://plnkr.co/edit/yYq1dt幫助這個

$scope.detailView = function(index){ 
    $scope.rowNumber = index 
    } 
+0

你也可以使用對象本身作爲指標 '' – Icycool