【问题标题】:AngularJS Multidimensional array Order ByAngularJS 多维数组 Order By
【发布时间】:2017-07-07 01:03:20
【问题描述】:

我有一个要解析为 JSON 的多维数组,我想在 AngularJS 中“排序”。我收到此错误:错误:[orderBy:notarray] Expected array but received: 13

<div ng-repeat="x in thread track by x.Id | orderBy: x.Id">

这是我的 JSON:

{
  "13": {
    "Id": 16,
    "LINK_Id": 16,
    "Attachments": [
      {
        "AttachmentName": "Attachment.jpeg",
        "AttachmentLinkId": 6,
        "LinkType": "Thread",
        "ThreadId": 20
      },
      {
        "AttachmentName": "Attachment.txt",
        "AttachmentLinkId": 7,
        "LinkType": "Thread",
        "ThreadId": 20
      }
    ]
  },
  "16": {
    "Id": 16,
    "LINK_Id": 169
  },
  "19": {
  "Id": 19,
  "LINK_Id": 112

} }

如果有人能提供帮助,将不胜感激。

非常感谢,

【问题讨论】:

    标签: javascript php angularjs json multidimensional-array


    【解决方案1】:

    使用 orderBy Go through this 时有一些限制和规则。 Iterating an Object of Objects (Acting as an Associative Array or Hash)这个标题是你想要达到的。

    【讨论】:

      【解决方案2】:

      替换:

      <div ng-repeat="x in thread track by x.Id | orderBy: x.Id">
      

      与:

      <div ng-repeat="x in thread | orderBy: 'Id' track by x.Id">
      

      【讨论】:

        【解决方案3】:

        我不会在 $scope 内对数组进行排序(即使据我所知,您不需要动态排序),我宁愿在控制器中使用内置的 sort 方法对其进行排序Javascript(更快)。

        例如返回JSON后,

        angular.module('sample-app', [])
        
        .controller('SampleController', ['$http', '$scope', function($http, $scope) {
        
          $scope.test = 'Array Sort';
        
          $http.get('https://jsonplaceholder.typicode.com/posts/')
          .then(function(result) {
            
            // Order id DESC (change a and b position for ASC)
            result.data.sort(function(a, b){ 
              return b.id - a.id 
            });
            
            // inject into scope
            $scope.items = result.data;
          });
        
        }]);
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        
        <div ng-app="sample-app">
          <section ng-controller="SampleController">
            <h3>{{ test }}</h3>
            <ul>
              <li ng-repeat="item in items">
                {{ item.id }}
              </li>
            </ul>
          </section>
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-28
          • 2013-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-08
          相关资源
          最近更新 更多