3

Imagine the following JSON API:

[
  {
    "id": "1",
    "name": "Super Cateogry",
    "products": [
      {
        "id": "20",
        "name": "Teste Product 1"
      },
      {
        "id": "21",
        "name": "Teste Product 2"
      },
      {
        "id": "22",
        "name": "Teste Product 3"
      }
    ]
  }
]

Is there anyway for me to only return the products array with Angularjs?

I have a simple service calling the JSON:

services.factory("ProductService", function($http) {
    return {
        "getProducts": function() {
            return $http.get("/product/index");
        }
    };
});

That is being called in the controller like so:

components.success(function(data) {
  $scope.products = data;
});

But it returns the whole JSON as expected, I need it to return only the "products" array so I can iterate through it.

PS: This is merely a simple example to illustrate the problem, I realize that I could change the API to fit my needs in this case, but that's not the point.

2 Answers 2

3

You would just assign the products array to your scope property...

components.success(function(data) {
  $scope.products = data[0].products;
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yea I tried that already, it returns as "undefined" for whatever reason I can't explain.
Just noticed it's inside of an array. Updated answer.
Oh but of course. I feel dumb now. Thanks man! This is exactly what I was shooting for, simple and efficient.
1

You could customize it via a promise, and do it yourself.

"getProducts": function() { 
        var promise = $q.defer();
        $http.get("/product/index").success(function(data){
            promise.resolve(data && data.products);
        }).error(function(msg){  
            promise.reject(msg);
        })
        return promise.promise;
}

How to use:

getProducts().then(
  function(data) {
    $scope.products = data;
  },  
  function(msg){
     alert('error')
  }
);

3 Comments

Never worked with promises, I'll have to check it out. What am I supposed to do in the controller to get the data with a promise? the "success" doesn't exist in promises apparently.
Updated above. Just use promise.then(successFunc, errorFunc)
Interesting. I'll have to look into promises more in the future. For now, the accepted answer is a quick fix for what I was aiming for. Thanks for the tip, I'll keep it in mind in the future.

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.