Reputation: 93
I am trying to iterate over and search by id and return the other values corresponding to the id from a JSON object of the type shown below, by $resource in the controller. I am not understanding where am I wrong in this case? Please help!
This is the controller
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?
}
]);
The JSON is of the type :
{"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"
}
Upvotes: 1
Views: 790
Reputation: 77904
The AppListService.listAllApps().get();
returns promise i suppose. Sounds like you try to print before got actual data.
I would use following approach:
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;
}]);
Upvotes: 2
Reputation: 41510
Here is code that shows the extraction of the id values, based on your json.
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);
}
Here is a jsFiddle giving an example of this extraction, integrated with Angular.
This code assumes that the JSON returned by your service is identical to what you have shown. Please note - there were initially some extra and missing commas in your JSON text (which I subsequently fixed), which may have also contributed to the errors that you were seeing.
Upvotes: 1