Display data from sqlite DB with AngularJS - javascript

I like to collect data from an android app and store them into sqlite DB - no problem so far.
But now I want to list these data using AngularJS, ng-repeat command.
I take the data from the DB via db.transaction(function(tx) tx.execSql...) but now how to format the data rows so that ng-repeat can read them ?
I tried an array of objects, I tried building a JSON string - both not working, I got a ngRepeat error.
var app = angular.module('demo',[]);
app.controller("MainController", function($scope){
// gets the tasks from the DB as json object
db.transaction(function(tx){
tx.executeSql("SELECT task,task_detail,task_date FROM task", [],
function(tx, rs){
var rows = rs.rows;
if (rows.length>0) {
var json_arr = [];
for(var i = 0; i < rows.length; i++) {
var row = rows.item(i);
var obj = {task: row.task,detail:row.task_detail,datum:row.task_date};
json_arr.push(obj);
}
}
var json_str = JSON.stringify(json_arr);
alert("json_str: "+ json_str); // WORKING !
sessionStorage.tasks = json_arr; // to get result out of db.transaction...
})
}); // end db.transaction
$scope.tasks = sessionStorage.tasks;
-> when i display {{tasks}} it appears as: [object,object]
and ng-repeat doesnt work
Otherwise if i use the stringified json, it displays correctly in {{tasks}} but ng-repeat causes again error.
Another real "dirty" way to get the result of the query into $scope is the sessionStorage thing - I dont like it this way but I cant see another possibility to set the $scope variable to the JSON (or whatever) result of the DB query. Maybe someone has a better idea ? ;)
Any ideas ? Thanks a lot, Chris

Related

Sending large Model list from view to controller c# mvc razor

I have got very large model list in view and i would like to send the list back to controller using ajax query. I have tried to send the whole model list back but since the model is too large, it exceeds the json maxlength specified within web.config. The encode method works for smaller list though.
var jsonString = #Html.Raw(Json.Encode(Model.modelName_small));
Only way that i can vision it to work is but filtering the large model list into smaller list using javascript (similar to a 'Where' SQL statement). My script are as follows (razor):
<script type="text/javascript" language="javascript">
function functionName(input1_decimal) {
var smallerList = new Array();
#foreach (var item in Model.modelName)
{
//input1_decimal should be within a certain range
#:if (input1_decimal - 0.1 <= #item.Property1) && (#item.Property1 <= input1_decimal + 0.1)
{
#:smallerList.push("#item");
}
}
//convert smallerList to json and send it to controller
}
<script>
it seems quite straight forward but I just can not get it to work. Might be something quite trivial. I have also tried:
var smallerList= Model.modelName.Where(x => (input1_decimal - 0.1 <= x.Property1) && (x.Property1 <= input1_decimal + 0.1));
Similarly, i have also tried
var smallerList = Model.modelName.filter(function (item) {
return (input1_decimal - 0.1 <= item.Property1) && (item.Property1<= input1_decimal + 0.1)
});
Thank you for your patience. i hope i have explained it clearly as to what i am trying to achieve. I am not a developer. Programming just for fun and self education.
Are you modifying data on the view ? If so, one other approach is to post only modified data to the controller in order to minimized the json string length and retrieve the rest of the data directly in the controller.
instead of editing jsonmaxlength field within web.config, I assigned MaxJsonLength to Int32.MaxValue. Created a list and assigned properties to model properties and serialise into Json object list. Then i filtered the list using $.grep function. Finally, I was able to send objJsonSmallList back to controller... Happy days :)
#{
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue;
//Create a list and assigning all the properties of the model
var data = Model.model_Name.Select(x => new
{
propName1 = x.property1,
propName2 = x.property2,
...
propNameN = x.propertyN
});
//serialize collection of anonymous objects
string strArr = js.Serialize(data);
}
var objJsonBigList = JSON.parse('#strArr'.replace(/"/g, '"'));
//small Filtered list send to controller via Ajax
var objJsonSmallList = $.grep(objJsonBigList, function (n) {
return ((input1_decimal- 0.1 <= n.Prop) && (n.Prop <= input1_decimal + 0.1))
});

How to display Firebase query result in HTML (undefined error)

I am trying to display Firebase query results in HTML but the browser shows "undefined" instead of the value that I see in the console.
var showData = document.getElementById("showData");
var button1 = document.getElementById("but1");
var usersRef =
firebase.database().ref('stores/').orderByChild("sid").equalTo(123);
function s2_but() { //function gets trigger when button pressed
usersRef.on('value', snap);
function snap(data) {
data2 = data.val();
console.log(data2);
showData.innerHTML = data2.sname; //sname is the name of child key
//whose value I want to show
}
};
Here is what the console shows:
entry1: {prod1: "coffee", prod2: "sandwich", sid: 123,
sname: "Java Coffee"}
__proto__:Object
Therefore, I am able to retrieve the data but I get an undefined in the browser when I use the following code to show the data in HTML.
<p id="showData"></p>
Undefined variable showing in the web-browser
I think the error happens when I am trying to call the exact value from the object using the following code but I am not sure. All the examples I have seen have done it this way. Therefore, I am confused.
showData.innerHTML = data2.sname;
In the HTML file I have both Firebase and jquery appropriately included, initialized etc.
I would greatly appreciate any help. Thanks.
I found the solution:
function snap(data) {
data2 = data.val();
data3 = data2.entry1.sname;
console.log(data3);
showData.innerHTML = data3;
};
Firebase returns a nested object with this query. entry1 is the name of the first level or key of this object. Therefore, its name has to be entered before accessing the value.
What to do if "entry1" were actually defined by a variable?
I think I was able to figure out the best way to do this. It took a while to understand the limitations of Firebase coming from an SQL background.
To query the database, I used this instead of using orderByChild():
var sid = 'entry1';
var usersRef = firebase.database().ref('stores/'
+ sid);
Now I am able to get the value of sname without having to enter the key of it in the chain:
function s2_but() {
usersRef.on('value', snap);
function snap(data) {
data2 = data.val();
data3 = data2.sname;
console.log(data3);
showData.innerHTML = data3;
};
};
This is to query a Firebase database entry that looks like this.
I hope this helps some of you looking to solve a similar problem. If you have any suggestions please let me know.

How to extract data from cookie using angular ngCookie?

I have cookie data printed in console now i want to create object that will get data from cookie firstname ,lastname,eamil and id. How i can create object when i recieve data in below format ?
mainCtrl.js
angular.module('angularModelerApp')
.controller('AccessCtrl',['$scope', '$cookies','UserAccessFactory',
function ($scope, $cookies,UserAccessFactory) {
$scope.newUser = {};
$scope.patternAttuid = new RegExp("^[a-z]{2}[0-9]{3}[a-z0-9]$");
$scope.cookie = $cookies.get('attESHr');
console.log('newUser',$scope.cookie)
});
data printed $scope.cookie
newUser Mike|Pierro|mp529u#us.att.com|||sl3561||mp529u,RHCRSMK,SBGPQX9,4131585|NNNNNNNNNNNNNNYNNYNNNNNN|MIKE|EY1PE2600|
You can use split to get the values separated. You should know that doing this is not encouraged because if the format changes, your code will be broken. But if you really need to parse that string, you could try this:
var parts = $scope.cookie.split("|");
$scope.newUser.firstName = parts[0];
$scope.newUser.lastName = parts[1];
$scope.newUser.email = parts[2];
// ... etc with all the other values, keeping in mind the index

Parse.com issues while querying array of pointers, .include not getting nested pointer data in cloud code

I am having trouble getting data from the nested pointers in my array of pointers from a query. I have an array of pointers like so: [{"__type":"Pointer","className":"QuizData","objectId":"rmwJrV55c7"},{"__type":"Pointer","className":"QuizData","objectId":"2132q8i9np”}, etc…]
That QuizData class also has a column named “ad” which is a Pointer to the “Ads” class. I can get the QuizData in a query using the following include statements on my query like so:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include("quizAdArr”);
__quizAdQueueQuery.include(["quizAdArr.QuizData"]);
BUT Neither of these or both combined don’t work as when I try to get column data from the ad it’s always undefined:
__quizAdQueueQuery.include(["quizAdArr.QuizData.ad"]);
__quizAdQueueQuery.include(["quizAdArr.QuizData.Ads"]);
This is my return from that query, where the column data "mediaType" that I am trying to access is always undefined:
return __quizAdQueueQuery.first().then(function(__resultsObj)
{
__quizQueueObj = __resultsObj;
__userQuizQueueArr = __quizQueueObj.get("quizAdArr");
var __quiz;
var __ad;
var __seenAd;
var __lengthInt = __userQuizQueueArr.length;
var __mediaTypeStr = __request.params.mediaType;
var __matchedQuizzesArr = [];
for (var __i = 1; __i < __lengthInt; __i++)
{
__quiz = __userQuizQueueArr[__i];
// console.log('__quiz.get("name") = '+__quiz.get("name"));
__ad = __quiz.get("ad");
// console.log("__ad.id = "+__ad.id);
//THE MEDIA TYPE IS ALWAYS RETURNING UNDEFINED HERE!!!
console.log('__ad.get("mediaType") = '+__ad.get("mediaType")+', __mediaTypeStr = '+__mediaTypeStr);
if (__ad.get("mediaType") == __mediaTypeStr)
{
//put all matches in array to be sorted
__matchedQuizzesArr.push(__userQuizQueueArr[__i]);
console.log("__matchedQuizzesArr.length = "+__matchedQuizzesArr.length);
}
}
return __matchedQuizzesArr;
});
Thanks for any help you can give! I also posted this as a bug in the Parse/Facebook issue reporter but was redirected here, so if this is a bug I can reopen it: https://developers.facebook.com/bugs/923988310993165/
EDIT Here is the updated, working query with nested includes for clarity:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include('quizAdArr');
__quizAdQueueQuery.include('quizAdArr.ad');
This should work (you only need to list the column names):
query.include('quizAdArr.ad');
Here's why:
You're querying QuizAdQueue so you don't need to list that
The QuizAdQueue class has an array in quizAdArr so you include it: query.include('quizAdArr');
Each quizAdArr element is a QuizData with an ad so you include it: query.include('quizAdArr.ad');
The issue was that you were including QuizData which is the name of a class and not a column name

Indexing firebase objects

How am I able to create an index for the object data that I am passing into Firebase?
I am using the .$add function in the AngularFire library to push the data. This is the filter and controller that I am using:
angular.module('bestDay', ["firebase"]).factory("GreatService", ["$firebase", function($firebase) {
var ref = new Firebase("https://quickjournal.firebaseIO.com/");
return $firebase(ref);
}])
.controller("bdctrl", ["$scope", "GreatService",
function($scope, greatService) {
$scope.theval = "Val " + Math.round(Math.random()*101);
$scope.daylist = greatService;
$scope.addDayGood = function() {
$scope.daylist.$add({
desc: $scope.newDay.desc,
date: $scope.newDay.date,
value: $scope.theval
});
$scope.newDay.desc = "";
$scope.newDay.date = "";
};
}
]);
As you can see, I was attempting to use a unique value when passing the objects in, but it was only generating the same number every time (13). If it isn't apparent, I am semi-new to programming.
I would also like to be able to write a function that will remove the data by that index. Since I am unable to conquer the prior task, I may need assistance in doing this as well.
I am writing my code with the angularjs library.
I have combed through the firebase and angularfire library documentation with no results. If you could point me to a URL with the documentation on this, it would be much appreciated.
Firebase should do the indexing, as this makes it easier if you have more than one user accessing the same data.
Relevant to your question, you should look up https://www.firebase.com/docs/ordered-data.html for working with lists in firebase.
More the point, the push() function provided makes for easy chronological sorting, and if you need more complex sorting you can look at the setWithPriority() function.
angular.module('bestDay', ["firebase"])
.controller("bdctrl", ['$scope', '$firebase',
function($scope,$firebase) {
var daysRef = new Firebase("https://quickjournal.firebaseIO.com/daylist/");
$scope.dayList = $firebase(daysRef);
$scope.dayLocationInFirebase = daysRef.push();
$scope.addDayGood = function(){
// Setdata to the generated location
$scope.dayLocationInFirebase.set({
desc: $scope.newDay.desc,
date: $scope.newDay.date
});
//holds reference to location the object was pushed to, for direct manipulation of the value. Pass it to the scope or an array if you need it for later
var pushedName = $scope.dayLocationInFirebase.name();
alert(pushedName);
$scope.newDay.desc = "";
$scope.newDay.date = "";
}
}
]);

Categories