簡體   English   中英

使用 ng-repeat 和過濾器時數組中對象的 $index

[英]$index of Object in Array while using ng-repeat and a filter

我對 angular 還很陌生,並且已經能夠有所了解。 但我似乎無法找到這種情況的答案......

我有一組對象,我正在從 firebase 中拉下它們。 我對對象使用 ng-repeat,然后相應地顯示數據。 我試圖將索引作為路由參數傳遞給“編輯”控制器。 在這種情況下,我想按照預期提取對象數據。 但是,當我過濾 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>

試試這個:

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

indexOf 總是在 ng-repeat 中返回原始索引

演示

不幸的是$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而不是其他任何東西。 希望這已經是記錄的一部分,您可以綁定到它而不是使用索引。

您可以使用函數從數組中返回索引

<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
}

在我的示例中,我有一個名為“posts”的對象數組,我使用過濾器按它們的一個屬性(“upvotes”屬性)對它們進行排序。 然后,在“href”屬性中,我通過引用傳遞它調用“getPostIndex”函數,即當前對象。

getPostIndex() 函數通過使用 Javascript 數組 indexOf() 方法簡單地從數組中返回索引。

這樣做的好處是,此解決方案不依賴於特定的過濾器(如@holographix 的答案),並且適用於所有過濾器。

我只是偶然發現了同樣的問題,我在 angular 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

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

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

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM