Advertisement
Guest User

Untitled

a guest
Nov 21st, 2014
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. angular.module('db.service', [])
  2. .factory("DBService", function($q) {
  3. var db;
  4. function openDb() {
  5. try {
  6. db = window.openDatabase("test", "", "test", 15000000);
  7. } catch (err) {
  8. alert("Error opening DB - " + err);
  9. }
  10. }
  11. function getAllEmployees(){
  12. var defer = $q.defer();
  13. var data = {"employees":[]};
  14. db.transaction(function(tx){
  15. var empQuery="SELECT Id,Name FROM employee ";
  16. tx.executeSql(empQuery,[],function(tx,results){
  17. var empLength=results.rows.length;
  18. for(var eIndex = 0; eIndex < empLength; eIndex++){
  19. var empId=results.rows.item(eIndex).Id;
  20. var emp=
  21. {"id":results.rows.item(eIndex).Id,
  22. "name":results.rows.item(eIndex).Name,
  23. "companies":[]
  24. }
  25. var companies=[];
  26. var companyQuery="SELECT comp.Name as CompanyName FROM company AS comp " +
  27. "LEFT JOIN employee_company_mapping AS ecm ON ecm.CompanyId = comp.Id " +
  28. "LEFT JOIN employee AS e on e.Id = ecm.EmployeeId " +
  29. "WHERE e.Id = "+empId;
  30. tx.executeSql(companyQuery,[],function(tx,compResults){
  31. var compLength=compResults.rows.length;
  32. for(var cIndex = 0; cIndex < compLength; cIndex++){
  33. var c={"name" :compResults.rows.item(cIndex).CompanyName}
  34. companies.push(c);
  35. }
  36. emp.companies.push(companies);
  37. data.employees.push(emp);
  38. },null);
  39. }
  40. defer.resolve(data);
  41. },null);
  42. });
  43. return defer.promise;
  44. }
  45. return{
  46. init:function(){
  47. return openDb();
  48. },
  49. fetch:function(){
  50. return getAllEmployees();
  51. }
  52. }
  53.  
  54. DBService.fetch().then(function(response){
  55. console.log(JSON.stringify(response);
  56. //putting the data in $scope
  57. // doing other things
  58. }
  59. );
  60.  
  61. {
  62. "employees":[
  63. {"id":1,"name":"Rosh","companies":[{"name":"google"},{"name":"ibm"}]},
  64. {"id":2,"name":"Pink","companies":[{"name":"asus"},{"name":"pizzahut"}]},
  65. {"id":2,"name":"Brahm","companies":[{"name":"tosiba"},{"name":"xiomi"}]}
  66. ]
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement