Angularjs ng-repeat数组与对象

时间:2014-11-06 10:05:36

标签: json angularjs arrays ng-repeat jsonobject

我正在使用ng-repeat来显示来自端点的视图中的原子数据形式的数据。如果Accept标头是'application / json',则此端点返回JSON,JSON是由服务器端的XML通过转换器创建的,遗憾的是,如果atom响应中有一个条目,则JSON中的条目不是数组, ng-repeat不能按预期工作。我有一个项目,我通过使用计数器手动处理,然后基于该计数器和ng-show我使用ng-repeat或只显示来自feed的单个条目。我该如何正确处理?我应该在JS方面修改传入的JSON吗?如果是的话,有人会指出我这样做的正确方法。

<feed xmlns="http://www.w3.org/2005/Atom">
 <id>/record</id>
 <title type="text">Search feed</title>
 <link href="/record" rel="self"/>
 <link href="/record?page=2" rel="next"/>
 <entry>
    <id>recordid</id>
    <link href="/record/id/recordid" rel="self"/>
    <content type="recordcontenttype">
        <record>...recordhere...</record>
    </content>
 </entry>
</feed>

{
"feed": {
    "entry": 
        {
            "content": {
                ...recordhere...
                },
                "type": "recordcontenttype"
            },
            "id": "recordid",
            "link": {
                "href": "/record/id/recordid",
                "rel": "self"
            }
        },

        -- if there would be more entries then entry would be an array [ { xx }, { xx } ] and ng-repeat would work --

    "id": "/record",
    "link": [
        {
            "href": "/record",
            "rel": "self"
        },
        {
            "href": "/record?page=2",
            "rel": "next"
        }
    ],

    "title": {
        "content": "Search feed",
        "type": "text"
    }
}
}

1 个答案:

答案 0 :(得分:1)

我建议使用一个简单的过滤器,例如:

(function (app, ng) {
  'use strict';

  app.controller('AppCtrl', function AppCtrl() {
    var vm = this;
    
    vm.foo = { id: 1 };
    vm.bar = [{ id: 2 }, { id: 3 }];
  });


  app.filter('ensureArray', function () {
    return function (input) {
      return ng.isArray(input) ? input : [input];
    };
  })
}(angular.module('app', []), angular));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>

<div data-ng-app="app" data-ng-controller="AppCtrl as app">
  <div data-ng-repeat="foo in app.foo|ensureArray">
    {{ foo|json }}
  </div>

  <div data-ng-repeat="bar in app.bar|ensureArray">
    {{ bar|json }}
  </div>
</div>