如何返回和数组中Angular.js一个JSON对象中 [英] How to return and array inside a JSON object in Angular.js

查看:148
本文介绍了如何返回和数组中Angular.js一个JSON对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下以下JSON API:

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"
      }
    ]
  }
]

反正我为返回产品与Angularjs阵列?

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

我有一个简单的服务调用JSON:

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

但它返回整个JSON不如预期,我需要它来只返回了产品数组,所以我可以通过它进行迭代。

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

PS:这只是一个简单的例子来说明这个问题,我意识到,我可以改变API,以适应在这种情况下我的需求,但是这不是问题的关键。

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

这篇关于如何返回和数组中Angular.js一个JSON对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆