繁体   English   中英

获取Angular的JSON数组中的第一项?

[英]Get the first item in a json array in angular?

我正在尝试从工厂调用的Web服务获取json数组中的第一项。

我的控制器:

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

我的服务:

'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}
    });
}]);

“ console.log($ scope.groups);” 返回:

[$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]

而“ console.log($ scope.groups [0]);” 只是返回“未定义”。

有什么方法可以获取该对象中的第一项?

getGroup返回了一个承诺。 尝试这个。

CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
function($scope, GetGroups){
   GetGroups.getGroups()
    .then(function(data){
      $scope.groups = data;
    });
}]);

然后,在“解决”该请求时,$ scope.groups将成为您从该请求取回的数据。

尝试这个。 它的工作..

 CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
    function($scope, GetGroups){
       $scope.groups = GetGroups.getGroups();
       $scope.groups.$promise.then(function(data) {
           alert(data[0].toSource());
       });

    }]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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