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.

1
  • 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 Commented Jul 27, 2015 at 13:42

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Additional question: how could I then sort array by id with javascript?
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.

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.