Your requirement is fetch how many rows which in your result, however, the query result may be asynchronous.
So, use $q to fetch the asynchronous result when $cordovaSQLite.execute() had been already fetch the result for your.
.factory('sqlitedata',function($q, $cordovaSQLite){
var sqlitedata = {};
var ink = 0;
// Create a deferred because the data you want will be return anytime
var deferred = $q.defer();
sqlitedata.getSqlData=function(){
var db= $cordovaSQLite.openDB("Ionic.db");
var query = "SELECT * FROM TABLE1 ";
$cordovaSQLite.execute(db, query).then(function(data) {
for(var i = 0; i < data.rows.length; i++) {
ink++;
}
// return ink;
// Okay, I (i.e the defferred) fetched the result,
// and I will resolve this promise and return it for you.
deferred.resolve(ink);
}, function (error) {
// return error;
// Error occurred, something is wrong when fetch the result,
// I (i.e. the defferred) can't keep my promise.
deferred.reject(error);
});
// return ink;
// Return a promise -- "I will return the result"
return deferred.promise;
}
return sqlitedata;
});
And then, fetch the result with $q.then()
$scope.btnClick3 = function () {
sqlitedata.getSqlData().then(function (result) {
console.log(result);
}, function (error) {
console.error(error);
} );
};
My main purpose to test this factory thing is because i want to get the sqlite json result from factory and use it at other factory therefore i can compare sqlite data with sqlserver data.
.factory('sqlitedata',function($q, $cordovaSQLite){
var sqlitedata = {};
var ink = 0;
var outputs=[];
// Create a deferred because the data you want will be return anytime
var deferred = $q.defer();
sqlitedata.getSqlData=function(){
var db= $cordovaSQLite.openDB("Ionic.db");
var query = "SELECT * FROM Table1 ";
$cordovaSQLite.execute(db, query).then(function(data) {
for(var i = 0; i < data.rows.length; i++) {
outputs.push({
"id" : data.rows.item(i).id,
"Item2" : data.rows.item(i).Item2
});
}
deferred.resolve(outputs);
}, function (error) {
deferred.reject(error);
});
// return ink;
// Return a promise -- "I will return the result"
return deferred.promise;
}
return sqlitedata;
});
Then use the return result into this factory
.factory('Factory2', function ($http, $q,dummydata,$cordovaSQLite,sqlitedata){
function getFactory2 () {
var result=[];
var deferred = $q.defer();
$http({
url: 'http://xxx.xx.xxx.xx:89/test/select_product.php',
method: "GET"
})
.success(function(data){
for(var i=0;i<data.length;i++){
//USE SQLITE RESULT HERE
angular.forEach( sqlitedata.getSqlData(),function(item) {
if(angular.equals(data[i], item)){
result.push({"id":data[i].id, "Item2":data[i].Item2});
}
});
}
deferred.resolve(result);
})
.error(function(err){
// console.log('Error retrieving markets');
deferred.reject(err);
});
return deferred.promise;
}
return {
getFactory2: getFactory2
};
})