在嵌套函数中设置组件范围变量

时间:2017-05-11 08:50:14

标签: angular

我正在尝试在组件中设置'records'变量,然后在'list.html'上查看它。我怎样才能实现它?

angular.module('myApp').component('listTransactions',{
    templateUrl:'list.html',
    controllerAs:'listTransCtrl',
    controller:function (){
    this.records=''; // I am trying to assign a value to this variable    
        var db = openDatabase(DATABASE_NAME, DATABASE_VERSION, DATABASE_NAME_VISIBLE, DATABASE_SIZE);
        db.transaction(function (tx) {
                tx.executeSql('SELECT * FROM '+TABLE_NAME, [], function (tx, result) {
                    var len = result.rows.length;
                    var transactions = [];
                    for (i = 0; i < len; i++) {
                        var transaction = result.rows.item(i);
                        transactions.push(transaction);
                    }

                   records=transactions;//How can I assign 'transactions' to variable 'records' in here ? 

                }, function (tx, error) {

                });

            });
    }
});

我的观点:list.html

<div style="text-align: center;">
    <span>{{listTransCtrl.records}}</span> <!-- Where I am expecting to see contents of 'records'-->
</div>

1 个答案:

答案 0 :(得分:1)

答案代码附于

下方
angular.module('myApp').component('listTransactions',{
    templateUrl:'list.html',
    controllerAs:'listTransCtrl',
    controller:function ($timeout){
        var vm = this;
        vm.records = '';

            var db = openDatabase(DATABASE_NAME, DATABASE_VERSION, DATABASE_NAME_VISIBLE, DATABASE_SIZE);
            db.transaction(function (tx) {
                    tx.executeSql('SELECT * FROM '+TABLE_NAME, [], function (tx, result) {
                        var len = result.rows.length;
                        var transactions = [];
                        for (i = 0; i < len; i++) {
                            var transaction = result.rows.item(i);
                            transactions.push(transaction);
                        }

                       $timeout(function() {
                           vm.records = transactions;
                           console.log(vm.records);
                        });


                    }, function (tx, error) {

                    });

                });
    }
});