在角度上迭代服务返回的JSON

时间:2013-11-10 08:16:24

标签: javascript json angularjs angularjs-resource

我正在尝试迭代并按id搜索,并通过控制器中的$ resource从下面显示的类型的JSON对象返回与id对应的其他值。在这种情况下,我不明白我错在哪里?请帮忙!

这是控制器

appSettings.controller('applistController', ['$scope', 'AppListService',
    function($scope, AppListService){
    // Have to iterate here to search for an id, how?
    // The Above app.json file is returned by the ApplistService(not showing the factory here as it works already.)
        $scope.allapps = AppListService.listAllApps().get();
    // console.log($scope.allapps.data) returns undefined as so does console.log($scope.allapps.length).
    // Where am I wrong?
    }
]);

JSON的类型为:

{"data":[
    {
      "id":"files_trashbin",
      "name": "TrashBin",
      "licence":"AGPL",
      "require":"4.9",
      "shipped": "true",
      "active":true
    },
    {
      "id":"files_external",
      "name": "External Storage",
      "licence":"AGPL",
      "require":"4.93",
      "shipped":"true",
      "active":true
    }
    ],
  "status":"success"
}

2 个答案:

答案 0 :(得分:2)

我认为AppListService.listAllApps().get();会返回承诺。听起来像是在获得实际数据之前尝试打印。

我会使用以下方法:

var appSettings = angular.module('myModule', ['ngResource']);

appSettings.controller('applistController', ['$scope', 'AppListService',
function($scope, AppListService){

     AppListService.listAllApps()
                        .then(function (result) {
                           $scope.allapp = result;                           
                        }, function (result) {
                            alert("Error: No data returned");
                        });  

}]);


appSettings.factory('AppListService', ['$resource','$q',  function($resource, $q) {

  var data = $resource('somepath', 
         {},
        { query: {method:'GET', params:{}}}
                 );


       var factory = {

            listAllApps: function () {
              var deferred = $q.defer();
              deferred.resolve(data);
             return deferred.promise;
            }

        }
        return factory;
}]);

答案 1 :(得分:1)

以下代码显示了基于json的id值的提取。

var json = '{"data":[{"id":"files_trashbin","name":"TrashBin","licence":"AGPL","require":"4.9","shipped":"true","active":true},{"id":"files_external","name":"External Storage","licence":"AGPL","require":"4.93","shipped":"true","active":true}],"status":"success"}';
$scope.allapps = JSON.parse(json);
$scope.ids = new Array();
var sourceData = $scope.allapps["data"];
for (var i=0; i<sourceData.length; i++) {
    $scope.ids.push(sourceData[i].id);
}

这是一个与Angular集成的an example of this extraction的jsFiddle。

此代码假定您的服务返回的JSON与您显示的内容相同。请注意 - 您的JSON文本中最初有一些额外的和丢失的逗号(我后来修复了这些逗号),这可能也导致了您看到的错误。