首页 > 解决方案 > 如何在 ngRepeat 中跳过 $$hashKey

问题描述

我正在尝试从对象动态创建一些表。这是我的对象

{
  categories: ["kids", "home"],
  home: [{
    name: "home 1.1",
    title: " home1.2"
  }, {
    name: "home 2.1",
    title: "home 2.2"
  }, {
    name: "home 3.1",
    title: "home 3.2"
  }, {
    name: "home 4.1",
    title: "home 4.2"
  }, {
    name: "home 5.1",
    title: "home 5.2"
  }],
  kids: [{
    name: "kids 1.1",
    title: "kids 1.2"
  }]
}

我的运行代码是

var app = angular.module("app", []);

app.controller("MainCtrl", function($scope) {
  $scope.data = {
    categories: ["kids", "home"],
    home: [{
      name: "home 1.1",
      title: " home1.2"
    }, {
      name: "home 2.1",
      title: "home 2.2"
    }, {
      name: "home 3.1",
      title: "home 3.2"
    }, {
      name: "home 4.1",
      title: "home 4.2"
    }, {
      name: "home 5.1",
      title: "home 5.2"
    }],
    kids: [{
      name: "kids 1.1",
      title: "kids 1.2"
    }]
  };


  $scope.getKeys = function(obj) {
    if (!$scope.data.hasOwnProperty(obj)) {
      return [];
    }

    return Object.keys($scope.data[obj][0]);
  }
});
<html ng-app="app">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
</head>

<body ng-controller="MainCtrl">
  <table ng-repeat="d in data.categories">
    <tr>
      <th ng-repeat="l in getKeys(d)" ng-if="$index != getKeys(d).length - 1">
        {{$index != getKeys(d).length - 1}} {{l}}
      </th>
    </tr>
    <tr ng-repeat="k in data[d]">
      <td>{{k.name}}</td>
      <td>{{k.title}}</td>
    </tr>
  </table>
</body>

</html>

正如您在示例中看到的,条件ng-if="$index != getKeys(d).length - 1"为假,但它显示了$$hashKey列。我怎么能跳过这个?

我尝试了这个答案的一些解决方案:

现在:

  1. 为什么这个条件是假的,但它显示了列?
  2. 获取每个表的列名的正确方法是什么?

标签: angularjsangularjs-ng-repeat

解决方案


您正在使用非常旧版本的 AngularJS。这个问题很久以前就从1.2.0我创建的以下示例中的版本检查中解决了,它适用于从1.2.0最新的 1.6.x 到所有版本的库

Plunker 示例


推荐阅读