0

我正在做一个从 SQLite 数据库加载的员工列表。我不知道为什么我的列表是空的,但我可以通过 JSON.stringify 看到数据正在发送。我正在使用 AngularJS 和 Cordova 框架。使用 Ripple 进行调试。

listEmployees.html

   <div data-role="page" apply-jq-mobile>    
            <div data-theme="a" data-role="header">
                <h3>
                    Header
                </h3>
            </div>
            <div data-role="content">
                <div class="ui-grid-a">
                    <div class="ui-block-a">
                    </div>
                    <div class="ui-block-b">
                        <a data-role="button" href="#/new" data-icon="plus" data-iconpos="left">
                            New
                        </a>
                    </div>
                </div>
                <input type="text" ng-model="search" class="search-query" placeholder="Search">
                <ul data-role="listview" data-divider-theme="b" data-inset="true">
                    <li data-role="list-divider" role="heading">
                        Employees
                    </li>
                    <li data-theme="c" ng-repeat="employee in employees">
                        <a href="#/edit/{{employee._id}}" data-transition="slide">{{employee.name}}</a>
                    </li>
                </ul>
            </div>
        </div>

员工控制

    function EmployeeCtrl($scope, Employee){

        $scope.employees = Employee.getAllEmployees();

        $scope.saveEmployee = function(id) {
            if(id){
                //TODO
            } else {
                Employee.addEmployee($scope.employee);
            }

        }
    }

员工

app.factory('Employee', function() {
    var data = {};
    data.addEmployee = function(_employee, callback) {
        var employee = new Employee();
        employee = _employee;
        DbService.db.employees.add(employee);
        DbService.db.saveChanges(callback);
    }

    data.getAllEmployees = function() {
        DbService.db.employees.toArray(function(employees) {
            console.log(JSON.stringify(employees));
            return employees;
        });
    };

    return data;
});
4

2 回答 2

0

我认为你需要使用承诺。您对 db 的调用是异步的,因此视图会在数据到达之前呈现。

data.getAllEmployees = function() {
    var $d = $q.defer();
    DbService.db.employees.toArray(function(employees) {
        console.log(JSON.stringify(employees));
        $d.resolve(employees);
    });
    return $d.promise;
};

Angular 模板系统在渲染之前等待所有的 Promise 得到解决。所以我认为这会解决你的问题。

于 2013-07-29T02:43:11.273 回答
0

所以,我解决了。

function EmployeeCtrl($scope, Employee){

    Employee.getAllEmployees(function(employees){
        $scope.employees = employees;
        $scope.$apply();
    });
}

.

app.factory('Employee', function() {
    var data = {};
    data.getAllEmployees = function(callback) {
        DbService.db.employees.toArray(function(employees) {
            callback(employees);
        });
    };

    return data;
});

谢谢你们!

于 2013-07-30T01:28:58.553 回答