0

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"
    }
}
}

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.