简体   繁体   中英

Get the first item in a json array in angular?

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?

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.

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

    }]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM