2013-07-29 56 views
0

我在做一個從SQLite數據庫加載的員工列表。我不知道爲什麼我的列表是空的,但我可以通過JSON.stringify看到數據正在處理。 我正在使用AngularJS和Cordova Framework。用紋波進行調試。AngularJS與列表

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> 

EmployeeCtrl

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; 
}); 

回答

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; 
}); 

謝謝大家!

0

我認爲你需要使用的承諾。您對數據庫的調用是異步的,因此視圖在您的數據到達之前得到呈現。

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

角模板系統在渲染前等待所有的承諾解決。所以我認爲這會解決你的問題。

+0

否...不起作用=/ –

+0

您需要在服務中注入$ q作爲依賴關係。如果它輸出到控制檯然後它應該工作 –

+0

我插入這裏:app.factory('員工',功能($ q)還有另一個位置,我應該注入? –