Ionic List populate data from Sqlite - angularjs

I am building an mobile application using Ionic and Sqlite.I am successful in storing data to the Sqlite database, retrieving the data back from the database and printing it to the console. Now, I am unable to figure out how to populate the data form the database in an ionic list
$scope.load = function() {
$cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
.then(
function(res) {
if (res.rows.length > 0) {
for (var i=0; i<res.rows.length; i++) {
console.log("Product ID: " + res.rows.item(i).productID + " Product Name : " + res.rows.item(i).productName);
}
}
},
function(error) {
console.log("Error on loading: " + error.message);
}
);
}
I need to display res.rows.item(i).productID & res.rows.item(i).productName in an ionic list.

Well, to answer my own question...it turns out to be actually very simple.It just works as normally as other Angularjs arrays. Made the following changes to my code:
$scope.load = function() {
$scope.listItems= [];
$cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
.then(
function(res) {
if (res.rows.length > 0) {
for (var i=0; i<res.rows.length; i++) {
console.log("Product ID: " + res.rows.item(i).productID + " Product Name : " + res.rows.item(i).productName);
$scope.listItems.push(res.rows.item(i));
}
}
},
function(error) {
console.log("Error on loading: " + error.message);
}
);
}
Now you can use ng-repeat or any other ionic element any display the data from sqlite as {{listItems}}.

Related

SQLite query sometimes not fetching all data

I am working on Ionic 1 project. I have applied a query to get data corresponding to the project ID but it is not returning all data sometimes. Sometimes the length is 1 or 2 or 6. It should return 6 always. What can be the issue?
self.getTeamMembersByProjectID = function(projectID) {
var parameters = [projectID];
return DBA.query("SELECT * FROM TeamMembers WHERE projectID = (?) ORDER BY displayName", parameters)
.then(function(result) {
return DBA.getAll(result);
});
};
I think you need to loop through the result first then push it to an array
I had a smilier issue before and this what I have done
$scope.ShowAllData = function() { /* SELECT COMMAND */
$scope.images = [];
$cordovaSQLite.execute(db,"SELECT * FROM imageTable ORDER BY id DESC").then( function(res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
$scope.images.push({
id: res.rows.item(i).id,
image: res.rows.item(i).images
});
}
}
}, function(error) {
alert(error);
} );
return $scope.images;
}

Cordova delete files after sqlite delete it

I have this app where I take picture or select it from gallery then move it into file-system , save the imgpath for the image into sqlite db and display it, everything works great so far , now when I delete the imgpath from the sqlite db , I want to delete it from file-system at the same time .
$scope.deleteImg = function(imgPath) {
if (!imgPath) {
console.error("No fileName specified. File could not be deleted.");
return false;
} else {
$cordovaFile.checkFile(cordova.file.externalRootDirectory, imgPath.id).then(function() {
$cordovaFile.removeFile(cordova.file.externalRootDirectory, imgPath.id).then(function(result) {
console.log("image '" + imgPath + "' deleted", JSON.stringify(result));
}, function(err) {
console.error("Failed to delete file '" + imgPath.id + "'", JSON.stringify(err));
});
}, function(err) {
console.log("image '" + imgPath.id + "' does not exist", JSON.stringify(err));
});
}
$scope.add = function(path) {
 
console.log("I AM ADDING TO DB WITH PATH: " + path);   
  
$cordovaSQLite.execute(db, "INSERT INTO imageTable (image) VALUES(?)", [path]).then(
function(res) {
console.log("I AM DONE ADDING TO DB");   
}
);                
      
},
function(e) {        
alert(e);      
};
    
  
$scope.ShowAllData = function() {
console.log("I AM READING FROM DB");   
$scope.images = [];             
$cordovaSQLite.execute(db,"SELECT * FROM imageTable ORDER BY id DESC"  ).then(        function(res) {
console.log("I FINISHED READING FROM DB");   
          
if (res.rows.length > 0) {            
for (var i = 0; i < res.rows.length; i++) {              
$scope.images.push({
id: res.rows.item(i).id,
image: res.rows.item(i).image
              
});
}          
} 
return $scope.images;
        
},         function(error) {          
alert(error);        
}      );
    
}  
$scope.getImgIDbyName = function(name) {
console.log('[getImgIDbyName] - get image with name: ' + name);
var sql = "SELECT * FROM imageTable WHERE image = '" + name + "';";
console.log(sql);
$cordovaSQLite.execute(db,
sql
).then(
function(res) {
if (res.rows.length > 0) {
if (res.rows.length > 1) {
console.log('[getImgIDbyName] - OOPS more than 1 image returned!!!! ' + name);
} else {
$scope.delete(res.rows.item(0).id);
$scope.deleteImg(imagePath.id);
}
} else {
console.log('[getImgIDbyName] - no image found with name: ' + name);
}
},
function(error) {
alert("error occured: " + error.message);
}
);
}
First download the plugin - cordova plugin add cordova-plugin-file
and then execute the following code
var path = cordova.file.applicationDirectory + '/www/res/image'; // get the absolute path
var filename = "image.png";
window.resolveLocalFileSystemURL(path, function(dir) {
dir.getFile(filename, {create:false}, function(fileEntry) {
fileEntry.remove(function(){
// The file has been removed succesfully
},function(error){
// Error deleting the file
},function(){
// The file doesn't exist
});
});
});
Here is the complete documentation : https://github.com/apache/cordova-plugin-file/#where-to-store-files

how to get ng-admin filters working with loopback API

I am new to ng-admin and angularjs. I am trying to integrate ng-admin with loopback for admin panel.
I am unable to get ng-filters filters working with loopback
because of this i think the reference_list and other filter are not working properly.
The problem is that i am unable to include where filter in my request to api
i am trying to do it using restangular
below is the code
// custom filters
if (params._filters) {
for (var filter in params._filters) {
params['filter[where]'] = "{" + entry.field + ":" + rams._filters[filter] + "}";
}
delete params._filters;
}
for "where" filter can be something like this:
for(var entry in params._filters) {
if (params._filters[entry] !== undefined) {
if (params._filters[entry].constructor === Array && params._filters[entry].length > 1) { // where value in array of values
params['filter[where][' + entry + '][inq]'] = params._filters[entry];
}
else { // where entry = value
params['filter[where][' + entry + ']'] = params._filters[entry];
}
}
}
Here's my entire interceptor for handling paging, sorting and filtering with loopback. Hope it saves someone time. Note that filters on relational fields ending with 'id' are processed using equality, whereas filters on other fields use 'like'.
myApp.config(['RestangularProvider', function (RestangularProvider) {
RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params) {
if (operation == "getList") {
// custom pagination params
if (params._page) {
params["filter[skip]"]= (params._page - 1) * params._perPage;
params["filter[limit]"] = params._perPage;
}
delete params._page;
delete params._perPage;
// custom sort params
if (params._sortField) {
params["filter[order]"] = params._sortField + " " + (params._sortDir || 'ASC');
delete params._sortField;
delete params._sortDir;
}
// custom filters
if (params._filters) {
var filterClause = "";
var i = 0;
for (var filter in params._filters) {
if (filter.endsWith('id')) {
params["filter[where][and][" + i + "][" + filter + "]"] = params._filters[filter];
} else {
params["filter[where][and][" + i + "][" + filter + "][like]"] = '%' + params._filters[filter] + '%';
}
i++;
}
delete params._filters;
}
}
return { params: params };
});
}]);

AngularJS ng-repeat view not updating after data update

have a some data one my page that is in a ng-repeat.
When the page and data 1st loads the data shows up.
When I move away from the page (using Angular Routing) make a change to the data (gets saved in db) then come back into the page (make call to db get new data) the ng-repeat data does not refresh. I can see the new data loading into the array and it is the new data.
I start the process on the page with
var sp = this;
sp.viewData = [];
sp.employee = [];
sp.ViewDataTwo = [];
$(document).ready(function () {
var testHeader = setInterval(function () { myTimer() }, 1000);
function myTimer() {
if (addHeaderToken() != undefined) {
clearInterval(testHeader);
sp.usageText = "";
if (sessionStorage.getItem(tokenKey) != null) {
sp.associatedInfo = JSON.parse(getassociatedInfo());
loadDataOne();
loadDataTwo();
}
}
}
});
I do this because I need to get my security toke from a JS script that I have no power over changes. So I need to make sure the code has ran to get me the token.
here are the functions I call..
function loadPasses() {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
$http.get('/api/Employee/xxx', { params: { employeeId: sp.employeeId } }).then(function (data) {
sp.viewData = data.data;
for (var i = 0; i < $scope. viewData.length; i++) {
sp.passes[i].sortDateDisplay = (data.data.status == "Active" ? data.data.DateStart + "-" + data.data[i].DateEnd : data.data[i].visitDate);
sp.passes[i].sortDate = (data.data[i].status == "Active" ? data.data[i].DateStart: data.data[i].visitDate);
}
});
}
function loadDataTwo () {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
if (sessionStorage.getItem(tokenKey) != null) $http.get('/api/Employee',
{
params: { employeeId: sp.employeeId }
}).then(function (data) {
sp.employee = data.data;
var tempPassString = "";
sp.ViewDataTwo = [];
var totalA = 0;
var totalU = 0;
for (var p = 0; p < sp.employee.dataX.length; p++) {
sp.ViewDataTwo.push(sp.employee.dataX[p].description + "(" + /** math to update description **// + ")");
totalA += parseInt(parseInt(sp.employee.dataX[p].Anumber));
totalU += parseInt(sp.employee.dataX[p].Bnumber));
}
sp.usageArr.push(" Total: " + totalA- totalU) + "/" + totalA + " Available");
//$scope.$apply();
});
}
One my view sp.viewData and sp.ViewDataTwo are both in ng-repeats.
Works well on load.. when I go out and come back in. I see the data reloading. But the view does not.
I have hacked the Dom to get it to work for now. But I would like to do it the right way..
Any help.
I have used
$scope.$apply();
But it tells me the digest is already in process;
the views are in a template..
Please help

How to show multiple records fetched from a table in parse.com

I am using Parse for my app. I have two tables StudentDetail and Subject,as user enters his name, the id is queried from studentDetail table. and using that id i want to fetch rest of the details of Subject table.Data fetched through this code is correct but in $scope.subs i.e 19th line it overrides the data and returns only the last record,i want to store all the records in $scope.subs object iteratively.
$scope.subjectFetch= function(form,form1) {
var query = new Parse.Query(StudentDetail);
var querySub = new Parse.Query(Subject);
query.equalTo("Firstname",form1.Firstname);
query.find({
success: function(results) {
stdId = results[0].id;
querySub.equalTo("StudentId",stdId);
querySub.find({
success: function(subjects) {
alert("Success");
for (var i = 0; i < subjects.length; i++) {
var object = subjects[i];
subname = object.get('Name');
credits = object.get('credits');
code =object.get('code');
duration = object.get('duration');
alert("Subject name: "+subname+"\n Credits :"+credits+"\n Code :"+code+"\n Duration:"+duration);
$scope.subs=[{Name:subname,credits:credits,code:code,duration:duration},{Name:"xyz",credits:5}];
//console.log($scope.subs);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
You are setting $scope.subs to be a new array with a single object in it inside your loop, which is why only the last one is there when it is done.
Try the following success handler instead:
success: function(subjects) {
// reset subs array
$scope.subs = [];
for (var i in subjects) {
var subject = subjects[i];
// push new object into the array
$scope.subs.push({
Name: subject.get('Name'),
credits: subject.get('credits'),
code: subject.get('code'),
duration: subject.get('duration')
});
}
// log the populated array
console.log($scope.subs);
Alternatively if you use something like the Underscore library, you can just map the items:
// replace success function body with this:
$scope.subs = _.map(subjects, function(subject) {
return {
Name: subject.get('Name'),
credits: subject.get('credits'),
code: subject.get('code'),
duration: subject.get('duration')
};
});
console.log($scope.subs);

Resources