Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I am using ng-repeat to display data in a View coming from an endpoint in a form of atom feed. This endpoint returns JSON if Accept header is 'application/json', that JSON is created from XML on a server-side by an converter, unfortunately if there is one entry in the atom response then the entry in the JSON is not an array and ng-repeat does not work as expected. I had a project where I handled this manually by using a counter and then based on that counter and ng-show I either used ng-repeat or just displayed the single entry from the feed. How do I handle this correctly? Should I rework the incoming JSON on JS side? If yes could someone point me the right way of doing that.

<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"
    }
}
}
share|improve this question

1 Answer 1

up vote 1 down vote accepted

I'd suggest a simple filter, e.g.:

(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>

share|improve this answer
    
All good, thank you. – Marcin Nov 6 '14 at 11:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.