【问题标题】:Modify $index value after each iteration in ng-repeat在 ng-repeat 中每次迭代后修改 $index 值
【发布时间】:2017-08-05 20:01:38
【问题描述】:

我的要求是在 angularjs 中每次迭代 ng-repeat 后递增 $index 值。我尝试像这样使用 ng-init 递增, 但它不起作用,并且在 ng-repeat 开始时递增。有人可以帮我解决这个问题吗?

   

 <div class ="row" ng-repeat ="offer in offers track by $index" ng-init="$index=$index+5">
    <div class="col-md-6">
   <span>offers[$index].title</span>
    <span>offers[$index+1].title</span></div>
    <div class="col-md-4"><span>offers[$index+2].title</span>
    <span>offers[$index+3].title</span>
    <span>offers[$index+4].title</span></div>
    </div>

问题我使用一行,在第一行交替显示两个标题,在第二行显示其他三个报价的标题。第一次迭代按顺序打印标题。但在第二次迭代中,它复制了数据因为 $index 的值为 2。所以我需要操作 $index 的值,以便它按顺序显示标题。

【问题讨论】:

  • 你用计数做什么?你能不使用$indexoffers.length吗?
  • 我有一个要求,我必须在每次迭代后跳过数组中的前 5 个项目。例如,对于第一次迭代,它应该呈现前 5 个项目,然后对于第二次迭代,它应该跳过前 5 个项目并从第 6 项开始渲染
  • 这最好使用过滤器来处理,您能否更好地概述您要使用offerscount 变量做什么?

标签: javascript angularjs


【解决方案1】:

AngularJs 为每次迭代提供索引值,您可以使用该索引值并更改计数。

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
Count =  {{count}}
<h1 ng-repeat="x in records  track by $index">{{x}} {{$index}} Count : {{count+$index}}</h1>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.count = 5;	

  $scope.records = [
    "Iteration : ",
	"Iteration : ",
  	"Iteration : ",
	"Iteration : ",
  ]
});
</script>

</body>
</html>

Chech That AngularJs Doc Link

【讨论】:

    【解决方案2】:

    尝试以下方法:

    var myApp = angular.module('myApp', []);
    myApp.controller('myController', ['$scope', function($scope){
      $scope.offers = [{title: 'Title 1'},{title: 'Title 2'},{title: 'Title 3'}];
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app='myApp' ng-controller='myController'>
      <div ng-repeat ="offer in offers">
        <span>{{offers[$index + 0].title}}</span>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多