Reputation: 55
I am trying to get the first item in a json array that i get from a web service i call with a factory.
My controller:
CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
function($scope, GetGroups){
$scope.groups = GetGroups.getGroups();
console.log($scope.groups);
console.log($scope.groups[0]);
$scope.group1 = $scope.groups[0];
}]);
My service:
'use strict';
var Groups = angular.module('GroupsService', ['ngResource']);
Groups.factory('GetGroups', ['$resource',
function($resource){
return $resource('../../../api/Groups/GetGroups', {}, {
getGroups : {method : 'GET', params:{}, headers: {'Accept': 'application/json;charset=UTF-8'}, isArray : true}
});
}]);
the "console.log($scope.groups);" returns:
[$promise: Object, $resolved: false]
0: Resource
groupId: "361552"
groupName: "1"
__proto__: Resource
>1: Resource
>2: Resource
>3: Resource
>4: Resource
>5: Resource
$promise: Object
$resolved: true
length: 6
__proto__: Array[0]
While the " console.log($scope.groups[0]);" just returns "undefined".
Is there any way to get the first item in that object?
Upvotes: 0
Views: 5304
Reputation: 931
Try this. Its working..
CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
function($scope, GetGroups){
$scope.groups = GetGroups.getGroups();
$scope.groups.$promise.then(function(data) {
alert(data[0].toSource());
});
}]);
Upvotes: 1
Reputation: 35276
getGroup is returning a promise. Try this.
CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
function($scope, GetGroups){
GetGroups.getGroups()
.then(function(data){
$scope.groups = data;
});
}]);
then when that request is 'resolved', $scope.groups will then become the data that you got back from that request.
Upvotes: 2