【问题标题】:Get ng-repeat to use object property order获取 ng-repeat 以使用对象属性顺序
【发布时间】:2013-12-30 11:01:50
【问题描述】:

我有一个动态数据集要与 Angular 一起呈现。换句话说,直到运行时我才能访问返回的列名。

我可以毫无问题地将列名作为标题和数据本身呈现。 ng-repeat (或者可能是 JS 本身)虽然拒绝按照创建的顺序返回列。您可以在小提琴中看到列已排序,因此它们显示为“年龄名称权重”,我需要它们来的方式,“名称年龄权重”

我创建了另一个列名及其正确顺序 ($scope.order) 的数组,但我似乎无法找到一种方法来使用 Angular 对数据进行排序。

请给我一种按原始顺序呈现这些数据的方法。

我创建了一个 JSFiddle:http://jsfiddle.net/GE7SW/

这是一个设置数据的简单范围:

function MainCtrl($scope) {
$scope.output = [
    {
        "name": "Tom",
        "age": "25",
        "weight" : 250
    },
    {
        "name": "Allan",
        "age": "28",
        "weight" : 175
    },
    {
        "name": "Sally",
        "age": "35",
        "weight" : 150
    }
];

$scope.order = {
    "name": 1,
    "age": 2,
    "weight" : 3
};           
}

这是 HTML:

<table ng-app ng-controller="MainCtrl">
  <thead>
    <tr>
      <th ng-repeat="(key,value) in output.0">{{key}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in output">          
      <td ng-repeat="(key,value) in row">{{value}}</td>
    </tr>
  </tbody>
</table>

(请注意,我为本示例提取的 ng-class 代码需要最后一个 ng-repeat 中的 (key,value)。)

【问题讨论】:

  • 你看过我的回答了吗?一切顺利吗?

标签: angularjs


【解决方案1】:

永远无法保证 JavaScript 对象中的属性顺序。您需要使用列表。

您唯一需要做的就是将$scope.order 转换为数组:

$scope.order = [
    "name",
    "age",
    "weight"
];

并像这样在 HTML 中使用它:

<table ng-app ng-controller="MainCtrl">
  <thead>
    <tr>
        <th ng-repeat="key in order">{{key}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in output">          
      <td ng-repeat="key in order">{{row[key]}}</td>
    </tr>
  </tbody>
</table>    

Fiddle

【讨论】:

  • 呃。我非常关注 Angular orderBy 解决方案,我完全错过了这一点。它实际上也简化了代码的其他部分。
  • 很棒,但如果对象是由其他开发人员编写的,在您的解决方案中,如果开发人员在名称上犯了错误,例如写 wieght 而不是 weight 订单将失败。
【解决方案2】:

Your updated fiddle here (click).

虽然无法保证 javascript 对象的顺序,但这可能适用于大多数或所有情况。这只是将您的对象循环到数组中。如果可能的话,将来自服务器的数据放在数组中可能是一种更好的方法,其中一个描述结构(键),另一个描述数组的数据集。

$scope.getRow = function(row) {
  var arr = [];
  for (var k in row) {
    if (k !== '$$hashKey') {
      arr.push(row[k]);
    }
  }
  return arr;
};
$scope.getKeys = function(row) {
  var arr = [];
  for (var k in row) {
    if (k !== '$$hashKey') {
      arr.push(k);
    }
  }
  return arr;
};

html:

<table ng-app ng-controller="MainCtrl">
  <thead>
    <tr>
      <th ng-repeat="(key,value) in getKeys(output[0])">{{value}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in output">          
      <td ng-repeat="(key, value) in getRow(row)" ng-class="getKeys(output[0])[key]">{{value}}</td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 我没有尝试过,但您的解决方案似乎适用于任何情况。我接受 CodeHater 的回答只是因为它更适合我的代码,而且我可以在另一部分轻松创建 order 数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
相关资源
最近更新 更多