Angularjs 将$scope.users.length获取为未定义

Angularjs 将$scope.users.length获取为未定义,angularjs,Angularjs,在getPagerLabel方法中,我对$scope.users.length进行了未定义,下面是代码 angular.module('myAppServices', ['ngResource']) .factory('Users', function($resource) { return $resource('/MY/system/users/grid'); }); function UsersCtrl($scope,

在getPagerLabel方法中,我对$scope.users.length进行了未定义,下面是代码

    angular.module('myAppServices', ['ngResource'])
        .factory('Users', function($resource) {
            return $resource('/MY/system/users/grid');
        });

    function UsersCtrl($scope, Users) {
        $scope.pagerLabel = 'Showing 1 - 10 of 100';
        $scope.users = Users.get();
        getPagerLabel();

        function getPagerLabel() {
            ...
            var total = $scope.users.length;
            ...
            //$scope.pagerLabel = 'Showing ' + start + ' - ' + end + ' of ' + total;
        }
get()返回json数据,如下所示

{"page":"1","total":"1","records":"3","rows":[{"loginId":1,"fullName":"Test User"},{"loginId":2,"fullName":"Some"},  {"loginId":3,"fullName":"TesterM"}],"expired":false}

这可能是因为Users.get()返回一个对象,而不是数组。您可以使用
$scope.users.records
,或
$scope.users.rows.length

更新:如果上述操作不起作用,则可能是您异步获取数据导致了问题。您可以尝试使用$q服务创建承诺。promise是一个可以按预期使用的对象,但在异步调用返回时将填充实际数据。以最简单的形式:

function getData(){
     var deferred = $q.defer();
     // async call, resolved after ajax request completes
     return deferred.promise;
};

getData().then(someOtherFunction);
//Angular also "understands" that it's a promise if you use it in a template like so
$scope.data = getData();
您可能想像上面其他人建议的那样使用.then()。
您可以在此处阅读更多内容:

好,这解决了问题

Users.get($scope.grid).$promise.then(function(result) {
            $scope.users = result;
            getPagerLabel();

        }, function(reason) {

        });

什么是
Users.get($scope.grid)返回?一个承诺?问题是,
Users.get()
返回什么?它是一个异步调用吗?而不是
$scope.Users=Users.get();getPagerLabel()
,尝试:
$scope.users=users.get()。然后(getPagerLabel)
。这意味着在
用户的数据返回之前调用了您的函数。get()
,这就是为什么它仍然未定义在这种情况下
$scope.users
不会未定义,我看不出他说用户未定义,只需
$scope.users.length
。“在getPagerLabel方法中,$scope.users.length未定义”。也许我错过了什么。顺便说一句-1不是我的