2015-07-20 47 views
0

我有一個HTML表格,其中包含使用ng-repeat和對象數組中的對象的數據屬性創建的行。它們按字母順序排列。我已經使用ng-show,ng-focus和ng-blur設置了一些簡單的編輯,因此不需要保存按鈕或類似的東西。ng-repeat元素的索引在排序時發生變化

但是,當我編輯名稱列時,如果鍵入第一個字母會導致該行在表格中較低,那麼它會對錶格進行排序,因爲我仍在鍵入。我嘗試創建一個「temp」對象數組,將原始數組複製到它中,編輯時修改「temp」數組,然後在編輯完成後將temp數組複製到原始數組中。這沒有用;無論如何,同樣的事情發生了。

經過一番研究,我瞭解到temp數組和原始數組都可能指向相同的數據,所以我嘗試了多種克隆數組的方法。我終於找到了工作......只有一個例外:當我編輯要排序的對象時,它移動了。當我試圖再次編輯它時,它做了各種隨機的,意想不到的事情。

經過一些診斷後,我發現表中的對象(從$ index獲得)的索引在排序時被更改。例如:

Table 
------------------------------------- 
|Name |Age  |Phone |Index | 
------------------------------------- 
|George |25  |928-7495|0  | 
|John |34  |342-0673|1  | 
|Megan |28  |834-1943|2  | 
|Susan |19  |274-8104|3  | 
------------------------------------- 

如果我將George更改爲Tim,則該對象的索引也會變爲3。所有其他指標保持不變。任何人都可以告訴我爲什麼會發生這種情況,並且/或者告訴我如何解決這個問題的建議?

+0

您是否無法控制「原始數組」的排序?它是通過過濾器完成的嗎?您需要提供一些示例代碼,以便我們可以知道發生了什麼。 –

+0

@Amine是的,我有一個過濾器,因爲我創建了表,以便我可以單擊每列的標題來更改排序。 – JFischer00

+0

需要一些代碼來看看你是如何實現它。 – SoEzPz

回答

0

顯然,我只是沒有意識到,每當我更改數據或數據排序時,索引都會發生變化。將索引作爲我的對象的屬性添加後,一切都按預期工作。

0

這就是我如何使用orderBy Angularjs過濾器的列類別,反過來點擊。 「th」中的「a」標籤控制着行爲。我有一個指令,這是建議,但代碼可以在控制器中。

我使用Angularjs orderBy過濾器作爲它們的狀態。

$filter('orderBy')(array, expression, reverse) 
// This is the order of properties in the code below that looks like this 
// $scope.rows = angularSortBy($scope.rows, columnName, toggleOrderDirection(columnName)); 

每列有一個名爲

<i class="fa fa-sort"></i> 

,其中,列會是這樣的一個字體真棒多箭頭切換...

$scope.columns = { columnOne: { label: 'Column One', orderDirection: true, selected: false }, 
    columnTwo: { label: 'Column Two', orderDirection: true, selected: false }, 
    columnThree: { label: 'Column Three', orderDirection: true, selected: true }}; 

和行可以是任何東西,你想...

<table> 
    <tr> 
    <th>Sort By</th> 
    <th ng-repeat="(key, value) in columns"> 
     <a href="" ng-click="orderBy(key)">{{ value.label }}</a> 
     <span ng-if="value.selected"> 
     (<i class="fa fa-sort"></i>) // font-awesome arrow font. 
    </th> 
    </tr> 

    <tr ng-repeat="row in rows">// stuff here</tr> 


var angularSortBy = $filter('orderBy'); // use Angular's built in filter to sort table. 

$scope.orderBy = function(columnName){ 
    resetAllSelectedStates(); // sets column.selected prop to false. 
    setAsSelected(columnName, true); 
    $scope.rows = angularSortBy($scope.rows, columnName, toggleOrderDirection(columnName)); 
} 

function resetAllSelectedStates(){ 
    Object.keys($scope.columns).forEach(resetColumnPropertyToDefault); 
} 

function resetColumnPropertyToDefault(name){ 
    $scope.columns[ name ].selected = false; 
} 

function setAsSelected(name){ 
    $scope.columns[ name ].selected = true; 
} 

function toggleOrderDirection(name){ 
    return $scope.columns[ name ].orderDirection = !$scope.columns[ name ].orderDirection; 
}