【问题标题】:How to obtain previous item in ng-repeat?如何在 ng-repeat 中获取上一项?
【发布时间】:2013-03-03 00:23:03
【问题描述】:

我有一个模板,只有当当前项目与前一个项目有一些不同的字段时,我才想在其中生成一些 HTML。如何访问 ng-repeat 中的上一个项目?

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:
    <li ng-repeat="item in items">
        {{items[$index - 1].att == item.att ? 'current same as previous' : 'current not same as previous'}}
    </li>
    

    【讨论】:

    • 对不起,我不认为这是对任何现有答案的改进。
    • 同意。如果没有解释为什么他们应该使用这种方法而不是 91 票赞成的答案,这个答案不会帮助任何人。这可能是一个很大的改进(我不是 angularjs 方面的专家)但没有解释,没有人会看到
    【解决方案2】:

    为什么不使用来自ng-repeatkey ? ($indexkey 相比似乎有些棘手)

    <div ng-repeat="(key, item) in data">
      <p>My previous item is {{ data[key-1] }}, my actual item is {{ item }}
    </div>
    

    【讨论】:

      【解决方案3】:

      你可以这样做

      <div ng-app="test-app" ng-controller="MyController">
          <ul id="contents">
            <li ng-repeat="content in contents">
                <div class="title">{{$index}} - {{content.title}} - {{contents[$index - 1]}}</div>
            </li>
          </ul>
      </div>
      

      JS

      var app = angular.module('test-app', []);
      
      app.controller('MyController', function($scope){
          $scope.contents=[{
              title: 'First'
          }, {
              title: 'Second'
          }, {
              title: 'Third'
          }]
      })
      

      演示:Fiddle


      小心: $index 用于指令数组,可能与作用域数组不同。使用内联变量访问正确的数组。

      <li ng-repeat="content in (correctContents = (contents | orderBy:'id'))">
        {{ correctContents[$index - 1] }} is the prev element
      </li>
      

      如果您过滤或排序,contents[$index] != content

      【讨论】:

      • 但是如果我在 ng-repeat 中有过滤器,那么这些集合会有差异。有什么想法吗?
      • @VadimAlekseev 您可以执行以下操作来引用过滤后的数据:ng-repeat="item in (filteredData = (data | filter:term))" 并在@arun-p-johny 的答案中使用filteredData[$index-1] 而不是contents[$index-1]
      • 我的收藏是一本字典,我无法按索引访问项目,有什么办法吗? :S
      • @a-matías-quezada 通过过滤器将对象动态转换为数组相当简单。见stackoverflow.com/questions/19387552/…。然后你可以使用 jpmorin 的评论来访问你的数据。
      【解决方案4】:

      一种方法是使用 $index 来定位上一个项目:

      HTML:

      <div ng-repeat="item in items">
        <span>{{$index}}: </span>
        <span ng-show="items[$index-1].name=='Misko'" ng-bind="item.name"></span>
      </div>
      

      JS:

      app.controller('AppController',
          [
            '$scope',
            function($scope) {
              $scope.items = [
                {name: 'Misko'},
                {name: 'Igor'},
                {name: 'Vojta'}
              ];
      
            }
          ]
        );
      

      Plunker

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-01
        • 2014-07-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多