2013-11-21 23 views
13

Im對於angular來說相當新穎,並且能夠稍微得到解決。但我似乎無法找到這種情況下的答案...

我有一個對象數組,我從firebase下拉。我正在使用ng-repeat作爲對象,然後相應地顯示數據。我試圖將索引作爲routeparam傳遞給「編輯」控制器。在這種情況下,我希望按照人們預期的方式提取對象數據。但是,當我篩選ng-repeat時,我得到了過濾內容的索引。我在哪裏找錯了真正的索引?

.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { 
$routeProvider 
    .when('/profiles/:index', { 
    templateUrl: '../views/profile.html', 
    controller: 'profileCtrl' 
    }); 

路徑的正上方,控制器低於

.controller('profileCtrl', function($scope, $routeParams){ 

$scope.teamProfile = $scope.ourTeam[$routeParams.index]; 
    $scope.index = $routeParams.index; 
}); 

最後的HTML代碼段從重複內。

<div class="profileName"><a href="/profiles/{{$index}}">{{member.name}}</a><span class="handle">{{member.handle}}</span></div> 
+2

您的意思是'{} {指數}'而不是'{{$指數}}'? – elclanrs

回答

10

可惜$index只是「迭代的重複元素的偏移量(0..length-1)」

如果你想在原來的指標,你就必須在此之前添加到您的收藏過濾或根本不過濾元素。

一個可行的方法:

angular.forEach(members, function(member, index){ 
    //Just add the index to your item 
    member.index = index; 
}); 

<div ng-repeat="member in members"> 
    <a href="/profiles/{{member.index}}"> 
</div> 

現在,它也似乎這種信息真的更像一個ID比什麼都重要。希望這已經是記錄的一部分,您可以綁定到該記錄,而不是使用索引。

+0

以及如果您通過字符串數組迭代會發生什麼?你將無法爲它添加屬性(索引)。 – vlio20

0

您可以注入$route並使用$route.current.params.index來獲取該值。

.controller('profileCtrl', function($scope, $route) { 

    $scope.index = $route.current.params.index; 

}); 
3

我只是碰到了同樣的問題,迷迷糊糊地我發現這個supertrick在agular git的問題

items.length - $index - 1 

<div ng-repeat="item in ['item', 'item', 'item'] | reversed"> 
     <!-- Original index: 2, New index: 0 --> 
     <p>Original index: {{items.length - $index - 1}}, New index: {{$index}}</p> 
     <!-- Original index: 1, New index: 1 --> 
     <p>Original index: {{items.length - $index - 1}}, New index: {{$index}}</p> 
     <!-- Original index: 0, New index: 2 --> 
     <p>Original index: {{items.length - $index - 1}}, New index: {{$index}}</p> 
    </div> 

,如果你有麻煩的時候像我給它一個拍攝:

https://github.com/angular/angular.js/issues/4268

+0

如果你不使用過濾器,這將是最好的解決方案。過濾器會搞砸你的索引。 –

6

你可以使用一個函數從數組

<div ng-repeat="post in posts | orderBy: '-upvotes'"> 
    <a href="#/posts/{{getPostIndex(post)}}"></a> 
</div> 

而且功能

$scope.getPostIndex = function (post) { 
    return $scope.posts.indexOf(post); //this will return the index from the array 
} 

在我的例子,我有一個名爲「上崗」對象的數組,關於這一點我使用返回索引過濾器按其屬性之一排序(「upvotes」屬性)。然後,在「href」屬性中,我通過將作爲參考(當前對象)傳遞給「getPostIndex」函數。

getPostIndex()函數只是使用Javascript數組indexOf()方法從數組中返回索引。

關於這一點的好處是,這個解決方案並不依賴於特定的過濾器(就像在@holographix答案中)並且可以適用於所有過濾器。

30

試試這個:

<div ng-repeat="member in members"> 
{{members.indexOf(member)}} 
</div> 

的indexOf總是返回原來的指數在NG-重複

Demo

相關問題