即使数据存在,angularjs中的数组长度也会返回零

时间:2014-12-03 11:48:41

标签: angularjs mongodb

JS:

    $scope.find = function() {
        $scope.onlyUsers = Users.query();
        console.log(" $scope.onlyUsers-->", $scope.onlyUsers);
        var len = $scope.onlyUsers.length;
        console.log('length',+len); 
        var peruser = [{}];
        if(data){
          for(var x=0; x< $scope.onlyUsers.length; x++){
            if( $scope.onlyUsers[x].orgId == $scope.authentication.user.orgId)
            peruser.push(data[x]);
            }
            }
            console.log('peruser--->',peruser);
          }
        }
    };

但是在console $ scope.onlyUsers数据即将到来。 控制台:

$scope.onlyUsers--> [] 0 Resource { __v=0, _id="547dc4a4ae31830800267e48", displayName="praveen Nune", more...}
1 Resource { __v=0, _id="547daf3bae31830800267e47", displayName="siva google12344545", more...} 2 Resource { __v=0, _id="547dae6eaf1a68c01c8020cc", displayName="siva acertis564e54354", more...}
3 Resource { __v=0, _id="547dabf151fc25a40124a9ff", displayName="microsoft google453234", more...}
4 Resource { __v=0, _id="547dab68571f9d0800bef142", displayName="e43545345 rtrgtr453", more...} 5 Resource { __v=0, _id="547da711078519dc14590cc4", displayName="microsoft acertis564e5", more...}
6 Resource { __v=0, _id="547da009a5a2493007f6a3de", displayName="microsoft acertis6786", more...} 7 Resource { salt=""?5???~?_?|?]?c", provider="local", role="54756bbc089822ac1fcd0226", more...}
8 Resource { __v=0, _id="547d983093b8cb181307751f", displayName="sap google56987", more...} 9 Resource { __v=0, _id="547d9605e9847d601062ea3f", displayName="mico admin", more...} 10 Resource { __v=0, _id="547d950ddbcdb90800a495d0", displayName="google user5678", more...}

并且长度为零。如何获得长度?... PLZ帮助我

length 0

2 个答案:

答案 0 :(得分:0)

当查询方法从服务器获取数据时,您必须传递一个回调函数来执行。

$scope.find = function () {
    $scope.onlyUsers = Users.query(function (result) {
        console.log(" $scope.onlyUsers-->", result);
        var len = result.length;
        console.log('length', +len);
        var peruser = [{}];
        if (data) {
            for (var x = 0; x < result.length; x++) {
                if (result[x].orgId == $scope.authentication.user.orgId)
                    peruser.push(data[x]);
            }
        }
        console.log('peruser--->', peruser)
    });

};

请参阅AngularJS docs

答案 1 :(得分:0)

这是异步数据加载问题。需要使用回调或延迟方法来解决此问题。控制台结果实际上只在数据提取完成后填充,但是你试图在数据加载完成之前获得数组的长度。