2016-07-29 92 views
1

我郵編數組:AngularJS採用NG-重複陣列關鍵的變化與過濾

var zipcodes = [ 
{ "Zipcode":"00501", "State":"NY", "City":"Holtsville" }, 
{ "Zipcode":"90210", "State":"CA", "City":"Beverly Hills" }, 
{ "Zipcode":"00544", "State":"NY", "City":"Holtsville" } 
]; 

我列出他們在一個表:

<input type="text" ng-model="query" placeholder="Search..."><br> 
<table> 
<tr ng-repeat="(key, zipcode_data) in zipcodes | filter: query" ng-click="edit_zip(key)"> 
<td>{{ zipcode_data.Zipcode }}</td> 
<td>{{ zipcode_data.City }}</td> 
</tr> 
</table> 

單擊行打開編輯對話框這工作正常...但是,如果我篩選數據,關鍵的變化。這會在編輯對話框中顯示來自原始數組的錯誤記錄(鍵)(如果過濾的列表發生重新排序)。

例如,如果我在城市'Holtsville'上過濾,將會顯示兩行,點擊第二個記錄發送鍵1,然而郵編數組鍵1爲90210

$scope.edit_zip = function(index) { 
$scope.index = index; 
var modal = ngDialog.open({ 
    scope: $scope, 
    template: 'zip_edit.html' 
}); 
} 

有沒有辦法保存在NG-重複原來的數組索引,以便它正確地結合正確的數組元件?

回答

1

始終使用zipcode_data永不index爲以後當你添加orderByfilter你會遇到問題,如index上沒有保留:

<input type="text" ng-model="query" placeholder="Search..."><br> 
<table> 
<tr ng-repeat="zipcode_data in zipcodes | filter: query" ng-click="edit_zip(zipcode_data)"> 
<td>{{ zipcode_data.Zipcode }}</td> 
<td>{{ zipcode_data.City }}</td> 
</tr> 
</table> 

和你的JS是這樣的:

$scope.edit_zip = function(item) { 
$scope.item = item; 
var modal = ngDialog.open({ 
    scope: $scope, 
    template: 'zip_edit.html' 
}); 
} 

注意: 你不應該嘗試一種方法來保留ng-repeat中的原始數組索引 - 如果你認爲關於它,你將無法使它與filter一起工作。

+1

謝謝......我沒有想過只是傳遞了zipcode_data,而這正是我需要的。 –