简体   繁体   中英

How to return and array inside a JSON object in Angular.js

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.

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

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

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')
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM