如何读取angularjs中的数组对象

时间:2016-10-24 07:13:27

标签: javascript angularjs ionic-framework

我要读取这个数组对象:

enter image description here

这些是我的示例代码:

$scope.obj_qst_local_study_main = tbl_qst_local_study_main.all();
$scope.quesion_id_allocated = $scope.obj_qst_local_study_main[0];
$timeout(function(){
    console.log('----------all objects----------');
    console.log($scope.obj_qst_local_study_main);
    console.log('-----------one object-----------');
    console.log($scope.quesion_id_allocated);
},200);

我用的时候:

$scope.obj_qst_local_study_main[0];

结果是:undefined

我的angularjs服务:

.service('tbl_qst_local_study_main', function($cordovaSQLite, DATABASE_LOCAL_NAME){
            var self = this;
            var qst_local_study_main_array = [];
            self.all = function() {
              var db = $cordovaSQLite.openDB({name: DATABASE_LOCAL_NAME,location:'default'});
                    $cordovaSQLite.execute(db, "SELECT * FROM qst_local_study_main")
                            .then(function (res) {
                                console.log('--------Successfully read from qst_local_study_main---------');
                                for (var i = 0; i < res.rows.length; i++) {
                                    qst_local_study_main_array.push(res.rows.item(i));
                                }
                            },
                                function (err) {
                                    console.log(err);
                                });
                    return qst_local_study_main_array;
            };
        })

1 个答案:

答案 0 :(得分:4)

您的服务应返回Promise。这是一个非常常见的案例,因为(请不要被冒犯)人们不理解Promises的工作方式。

请在互联网上搜索一篇文章,例如:https://developers.google.com/web/fundamentals/getting-started/primers/promises

tl; dr 您的服务应返回Promise。在您的情况下$cordovaSQLite.execute然后您可以通过链接then来正确处理响应。您也不需要超时。使用超时在这里非常糟糕!

tbl_qst_local_study_main.all()
  .then(function(result) {
    console.log(result);
  })