嵌套的 ng 重复显示错误的$index

nested ng-repeat showing wrong $index

本文关键字:错误 index 显示 ng 嵌套      更新时间:2023-09-26

>我尝试使用 ng-repeat,但当$index不断显示错误的东西时卡住了这是我的代码http://codepen.io/netwrkx/pen/VamRjo

<div ng-controller="ctrl">
    <div class="row responsive-sm " ng-repeat="items in DataAPI">
        <div class="card1" ng-repeat="item in items">
            <div class="row">
                <div class="">            
                    <input type="submit" ng-click="showFullPost($index)"></input>
                    <h4 class="post-title">{{item}} {{$index}}</h4>
               </div>
            </div>
        </div>
    </div>
</div>
function ctrl($scope){
    $scope.items = ["orange", "mango", "grape", "apple", "pineapple", "lemon"];
    $scope.DataAPI =  [["orange", "mango"],["grape", "apple"], [ "pineapple", "lemon"]];
    $scope.showFullPost = function(index){
                    console.log($scope.items[index] );
                    //$state.go('post');
                }
}

尝试循环

儿童$scope.items = ["orange", "mango", "grape", "apple", "pineapple", "lemon"];

$scope.DataAPI = [["orange", "mango"],["grape", "apple"], [ "pineapple", "lemon"]];

$index一直只显示橙色和芒果。 我错过了什么??

任何想法...

这将标记项目 0、1、2、3、4、5。

<div ng-repeat="items in DataAPI track by $index">
  <div ng-repeat="item in items" ng-init="idx = $parent.$index * items.length + $index">
    <button ng-click="showFullPost(idx)">View Full</button>
    <h4 class="post-title">{{item}} {{idx}}</h4>
  </div>
</div>

内部ng-repeat创建了一个新范围,在该作用域中填充了内部$index,因此以某种方式"阴影"了外部$index

一种解决方案是使用以下表示法访问父$index:

{{$parent.$index}}

通常,引用父范围的数据是不正确的做法,尤其是在定义多个嵌套控制器时。在这种情况下,我认为没关系。可能还有另一种方法可以重新定义用于索引的变量......

在这里我不确定你想做什么。

鉴于您正在使用ng-repeat="items in DataAPI"但您已经在内部循环中 controller.so $scope.items,您无法$scope.items访问控制器,因为内部循环已经从外部ng-repeat items

因此,请确保在内循环中需要什么。您想要控制器作用域中的项还是外循环作用域中的项?

如果您可以自由修改$scope.DataAPI,请尝试以 json 格式修改它,如下图所示:

$scope.DataAPI = [{"name": "orange"}, {"name": "mango"}, {"name": "grape"}, {"name": "apple"}, {"name": "pineapple"}, {"name": "lemon"}];

然后相应地访问数据。