1

我正在尝试通过 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"
}
4

2 回答 2

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;
}]);
于 2013-11-10T08:59:33.500 回答
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);
}

这是一个 jsFiddle,给出了一个与 Angular 集成的提取示例。

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

于 2013-11-10T08:50:30.200 回答