Batman Batman - 3 years ago 95
AngularJS Question

ng-repeat to handle both data as object and array

Can anyone help me with below query ?

Sometimes I will get the data as JSONObject and sometimes I will get the data as JSONArray during the time of ng-repeat it will only work with JSONArray but not with JSONObject situation Can you suggest me something here?

Here is the example this will show the value of _serviceID only when Service comes as an array but this won't work if Service section comes as an Object

<td class="features">
<span ng-repeat="indi in ServiceChanges.ServiceInstalls.Service">{{indi._serviceID}}<br></span>

Note : I don't want to use ng-if to check the length as it affects the position of my DOM in other DIV So is there any solution other than this kind of approach like converting object into array by adding dummy values?

Answer Source

You could convert the return response into an array in controller.

.controller(function ($scope) {
    // code here

    var serviceArray = [];
    var response = angular.copy($scope.ServicesChanges.ServiceInstalls.Service);

    if (angular.isObject(response)) {
        $scope.serviceArray = serviceArray;
    } else if (angular.isArray(response)) {
        $scope.serviceArray = response;
    } else {
        $scope.serviceArray = serviceArray;

    // code here

<td class="features">
    <span ng-repeat="indi in serviceArray">{{indi._serviceID}}<br></span>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download