0

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?

2
  • getGroup method is returning you the promise object not the data. try using something like GetGroups.getGroups().then(response){ $scope.groups = response}; Commented Apr 30, 2014 at 10:52
  • Thanks for this, I had seen something about this, but it gives me 'TypeError: undefined is not a function'. Any idea what that can be about? Commented Apr 30, 2014 at 11:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, I had seen something about this, but it gives me 'TypeError: undefined is not a function'. Any idea what that can be about?
1

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());
       });

    }]);

2 Comments

Thanks for this, I had seen something about this, but it gives me 'TypeError: undefined is not a function'. Any idea what that can be about?
Can you text that briefly, in which case you have got the TypeError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.