使用angularjs显示嵌套的JSON

时间:2015-02-03 22:45:45

标签: json angularjs

我正在尝试在页面中显示嵌套的JSON。我不知道如何深入研究它。

在我的app js文件中,我有一个名为initialData的参数,我希望在调用视图时调用函数getProducts()...

'use strict';
var quoteApp = angular.module('quoteApp', ['ui.router']);
quoteApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');
$stateProvider

    // HOME STATES AND NESTED VIEWS ========================================
    .state('home', {
        url: '/home',
        templateUrl: 'ng-views/choose.html',
        controller: "quoteBuilderController",
        resolve: {
            initialData: ['quoteApi', function (quoteApi) {
                return quoteApi.getProducts();
            }]
        }
    })
});

我的quoteApi看起来像这样,以防你想看到它......

(function () {
'use strict';

angular.module('quoteApp').factory('quoteApi', quoteApi);

quoteApi.$inject = ['$http'];

function quoteApi($http) {
    var service = {
        getProducts: getProducts,
        getPrices: getPrices
    };
    var baseUrl = 'http://www.website.com/api/Pricing';

    return service;

    function getProducts() {
        return httpGet('/GetProductCatalogue');
    }

    function getPrices() {
        return httpGet('/GetPrices');
    }

    /** Private Methods **/
    function httpExecute(requestUrl, method, data){
        return $http({
            url: baseUrl + requestUrl,
            method: method,
            data: data,
            headers: requestConfig.headers }).then(function(response){
            return response.data;
        });
    }
    function httpGet(url){
        return httpExecute(url, 'GET');
    }
}
})();

所以quoteApi.getProducts()返回看起来像这样的JSON ......

{
"Cat1": [
    {
        "product_id": 1,
        "product_name": "Prod1"            
    },
    {
        "product_id": 2,
        "product_name": "Prod2"
    }
],
"Cat2": [
    {
        ...
    }
]
}

我的视图控制器看起来像这样......

(function () {
'use strict';
angular.module('quoteApp').controller('quoteController', ['$scope', '$http', '$timeout', quoteController]);
quoteController.$inject = ['initialData', 'quoteApi'];

function quoteController($scope, initialData) {
    $scope.cat1Products = initialData;
};
})();

所以我的问题是,如何才能让'initialData'仅从Cat1加载产品?我应该尝试从HTML执行此操作吗?看起来它应该是直截了当但我似乎可以得到它。谢谢。

2 个答案:

答案 0 :(得分:1)

您需要进一步转换来自您的http请求的响应,以便您只返回所需的部分,并且您可能还需要考虑使用.then()方法:

$http.get('/someUrl').then(function(response) {
        //Do something with response.data.Cat1 here
      }, function(errResponse) {
        console.error('Error while fetching data');
      });

答案 1 :(得分:0)

从initialData对象中取出cat1

function quoteController($scope, initialData) {
    $scope.cat1Products = initialData['Cat1'];
};
相关问题