0

Create:

I am using $scope.services where I am storing my list of services. This is an array of objects:

$scope.services = [{
    title           : undefined,
    quantity        : undefined,
    pricePerUnit    : undefined,
    priceCalculated : undefined,
    order           : undefined         
}];

I can then push another object into array.

$scope.services.push({ 
    title           : undefined,
    quantity        : undefined,
    pricePerUnit    : undefined,
    priceCalculated : undefined,
    order           : undefined
});

So far, so good. I am then using this object as a model within Angular, to show its content.

Update:

I am calling API and getting my JSON in format:

{
    someData: "some data",
    services: {
        0: {
            id: 101,
            offer_id: 101,
            title: "some title",
            ...
        },
        1: {
            ...
        }
    }
}

Appending received data by $scope.services = data.services and then when I am calling $scope.services.push I get the console error

TypeError: $scope.services.push is not a function.

What could be wrong? Is it the JSON/array issue? I never got to the bottom of this, so any theory knowledge would be appreciated as well. Thank you in advance.

Huang Chen
  • 1,177
  • 9
  • 24
be-codified
  • 5,704
  • 18
  • 41
  • 65
  • Why create the array and then wipe it out when data is received that isn't an array? Also makes no sense using index keys as object properties inside your new data. Need to fine tune your data source output and make services properrty an array instead of object – charlietfl Jul 27 '15 at 13:42

2 Answers2

2

Because services is not an array, (push is defined for arrays: Array.prototype.push()) you need to construct a proper array from the response.

var servicesArray = [];
Object.keys(data.services).forEach(function (key) {
   servicesArray.push(data.services[key]);
}); 
$scope.services = servicesArray;
Can Guney Aksakalli
  • 1,320
  • 1
  • 11
  • 24
1

I think the object you assign(data.services) $scope.services = data.services may not be an array. Cross check whether your object from data.services is array. Found a similar issue (link) which may be helpful for you.

Community
  • 1
  • 1
Nandan P
  • 106
  • 4