Fetch data from sqlite and display it in autocomplete - angularjs

I'm working for iPhone application using phonegap. In the application there are few dropdowns whose values are more the 10000. Now we are trying to replace the dropdown with Autocomplete.
We are maintaining those 10000 records in SQLite DB and fetch the records from the DB as user enters the string.
CODE:
<input type ="text" class="inputFormText" ng-model="Location.location" id="location" list ="locValues" placeholder="{{'lSummary_Location_text'|translate}}" autocomplete = "on" maxlength="80" ng-keyup="populateLocations($event)"/>
<div class="aListCon">
<datalist id="locValues">
</datalist>
</div>
$scope.populateLocations = function($event){
if ($event.target.value.length > 2) {
try
{
db.transaction(function(tx){
tx.executeSql("SELECT ID, VALUE FROM tbl_Location WHERE VALUE LIKE '%" + $event.target.value + "%'", [],
function(tx, res){
if(res.rows.length > 0)
{
var template = "";
for (var i = 0; i < res.rows.length; i++) {
var id = res.rows.item(i).value + ' / ID: ' + res.rows.item(i).id;
template += '<option class="aCon" id="' + id + '" value="' + res.rows.item(i).value + '"></option>';
};
document.getElementById('locValues').innerHTML = template;
}
else
console.log("No records found")
},
function(ex){
console.log("Populate Location Error: " + ex.message);
});
});
}
catch(ex)
{
console.log("Populate Location Error: " + ex.message);
}
};
};
I was able to fetch the records form the SQLite and append to the datalist, but Autocomplete is not displayed in the UI.
Any idea where I'm going wrong?
Thanks in advance

This code should be working:
var divtoappend=angular.element( document.querySelector( '#locValues' ) );
divtoappend.append("<option class="aCon" id="' + id + '" value="' + res.rows.item(i).value + '"></option>");

Related

AngularJS Table Column Search...smarter ideas?

I have to use AngularJS to build a dashboard and one of the components is a table.
Since I did not find relevant dependencies/libraries for angularjs (like tabulator or datatables), I am doing it myself.
Instead of using the native angular filter, I built a custom method, but I am not sure if I am following a good approach.
The main idea is that when I pull the data object (array of objects) via Ajax, I create both an "original" and a "current" data object,s and at the beginning, they are exactly the same of course.
Then I created an input field above every column heading and I linked the search function to the blur and keyup events (enter key).
When the search function is triggered, I start making changes to the "current" object. This way I can filter by multiple columns incrementally. I filter the data object using an awesome library called AlaSQL.
I also linked to a button the "reset" method, which simply makes the "current" object equal to the "original" object, and cleans up the input fields.
The point is, am I missing any best practices? Are there better ways to do so with AngularJS?
Any suggestions?
Thanks a lot.
HTML
<div ng-app="myApp">
<div ng-controller="divController">
<my-table></my-table>
</div>
</div>
JS
var app = angular.module('myApp', []);
app.controller('divController', function ($scope, $http) {
$scope.data = {};
$scope.data.current = null;
$scope.data.original = null;
$scope.filter = {
id: {
field: "id",
value: null
},
name: {
field: "name",
value: null
},
owner: {
field: "owner",
value: null
},
}
$scope.reset = function () {
console.log("reset");
$scope.data.current = $scope.data.original;
for (let prop in $scope.filter) {
$scope.filter[prop]["value"] = null;
}
}
$scope.filterExec = function (field, value) {
if (value) {
console.log(`Executing filter on field "${field.trim()}" by this value "${value.trim()}"`);
var filtered = alasql('SELECT * FROM ? where ' + field + ' LIKE "%' + value + '%"', [$scope.data.current]);
$scope.data.current = filtered;
}
}
$http.get("./workspaces_demo_obj.json")
.then(function (response) {
console.log(response);
$scope.data.original = response.data;
$scope.data.current = response.data;
});
});
app.directive('myTable', function () {
return {
template:
'<div>Total rows {{data.current.length}} <button ng-click="reset()">RESET</button></div>' +
'<table class="table table-responsive table-sm">' +
'<thead>' +
'<tr><th>Workspace ID</th>' +
'<th>Name</th>' +
'<th>Owner</th></tr>' +
'<tr><th><input ng-model="filter.id.value" ng-blur="filterExec(filter.id.field, filter.id.value)" ng-keydown="$event.keyCode === 13 && filterExec(filter.id.field, filter.id.value)" placeholder="Filter by id"></input></th>' +
'<th><input ng-model="filter.name.value" ng-blur="filterExec(filter.name.field, filter.name.value)" ng-keydown="$event.keyCode === 13 && filterExec(filter.name.field, filter.name.value)" placeholder="Filter by name"></input></th>' +
'<th><input ng-model="filter.owner.value" ng-blur="filterExec(filter.owner.field, filter.owner.value)" ng-keydown="$event.keyCode === 13 && filterExec(filter.owner.field, filter.owner.value)" placeholder="Filter by owner"></input></th></tr>' +
'</thead>' +
'<tbody>' +
'<tr ng-repeat="x in data.current">' +
'<td>{{ x.workspace_id }}</td>' +
'<td>{{ x.name }}</td>' +
'<td>{{ x.owner }}</td>' +
'</tr>' +
'</tbody>' +
' </table>',
restrict: 'E'
};
});

Not able to get ng-model value from dynamically created input box

Here is how I am adding fields.
$scope.addEmailField = function () { //Function to add new email field.
if (valid <= 1 && checkToDelete == 0) {
var mailTxtId = 'mail' + valid;
var mailModel = 'Contact_Email' + valid;
var hide = 'hide' + valid;
hide = false;
console.log(mailTxtId);
var emailDiv = angular.element(document.querySelector('#emailDiv'));
var element = $compile('<div id="' + mailTxtId + '" style="margin-left: -60px; width:200px; margin-top:15px"><input id= "' + mailModel + '" type = "text" class="form-control" ng-model="' + mailModel + '" ng-blur="validateEmailDynamic(' + valid + ')">' +
'<input id="' + valid + '" class="form-control" style="margin-left: 206px; width:54px; margin-top:-34px" type="button" value="-" ng-click="deleteField(' + valid + ')"><span ng-show ="' + hide + '" style="color:red">' +
'Invalid email</span></div>')($scope);
emailDiv.append(element);
valid = valid + 1;
}
};
But not getting the value of ng-model.
Store your input box in a directive's template. Then add ng-class that would determine whether it should show or not.
app.directive('inputBox', function(){
template:'<input ng-model="item">'
});
Usage in the html:
<div ng-class="{ input-box : triggerInputBox }"></div>
Controller:
$scope.triggerInputBox = true;
This is just one of many ways to accomplish this. But directives are very useful for dynamically showing templates.

Widget for getting facebook group's timeline / posts

I want to integrate facebook Widget for getting facebook group's timeline / posts. I have searched & got this https://developers.facebook.com/docs/plugins/page-plugin but this gives user's & page's timeline. I wanted Group's timeline. I didn't found perfect answer on Fb Developer portal & didn't get anything on web.
Any help on this is appreciated.
Thanks in Advance.
After lots of search, no plugin kind of thing i got for this. But yes got one blog in php where the developer made custom widget manually, I modified it with JavaScript & jQuery.
<div style="height: 375px; background: #f6f7f9;">
<div id="fb-root"></div>
<p class="text-center media-body social-link" style="background: white">
<img src="~/Content/Images/Link-Red.png" />
Facebook Group
</p>
<div id="fix-div"></div>
<div id="facebook-group" style="overflow-y: scroll; height: 375px; margin-top: 55px;"></div>
</div>
Facebook JavaScript API as follows-
<script>
var access_token = '<!-- Valid fb access token -->';
var groupId = 'valid facebook group id';
window.fbAsyncInit = function () {
FB.init({
appId: 'valid facebook app id',
cookie: true,
xfbml: true,
version: 'v2.8'
});
FB.api("" + groupId + "?fields=cover,icon,name,privacy",
'get',
{ access_token: access_token },
function (groupResponse) {
if (groupResponse && !groupResponse.error) {
$("#fix-div").html('');
$("#facebook-group").html('');
var fixDivHtml =
"<div style='z-index: 10;position: absolute;border: 1px solid #e9ebee;max-width: 470px;background: white;min-height: 50px;'><div class='media' style='border: 0'><div class='media-left media-middle' style='vertical-align: bottom'><a href='https://www.facebook.com/groups/" + groupResponse.id + "' target='_blank'><img class='media-object' src='/Content/Images/Facebook-group.png' style='min-height: 50px;padding: 5px 10px;width: 64px;'></a></div><div class='media-body media-middle'><a href='https://www.facebook.com/groups/" + groupResponse.id + "' target='_blank'><h4 class='media-heading' style='font-size: 14px;font-weight: bold;'>" + groupResponse.name + "</h4></a></div></div></div>";
$("#fix-div").append(fixDivHtml);
FB.api("/" +
groupId +
"/feed?fields=id,message,link,attachments{media,description},created_time,from,object_id,parent_id&limit=1000",
'get',
{ access_token: access_token },
function (response) {
if (response && !response.error) {
for (var i = 0; i < response.data.length; i++) {
var picture = undefined;
var description = undefined;
var date = formatDate(response.data[i].created_time);
if (response.data[i].attachments !== undefined) {
if (response.data[i].attachments.data.length > 0) {
if (
response.data[i].attachments.data[0].media !==
undefined) {
if (
response.data[i].attachments.data[0].media
.image !==
undefined)
picture = response.data[i].attachments
.data[0].media.image.src;
if (
response.data[i].attachments.data[0].media
.image.description !==
undefined)
description = response.data[i].attachments
.data[0].media.image.description;
} else {
if (
response.data[i].attachments.data[0]
.description !==
undefined)
description = response.data[i].attachments
.data[0].description;
}
}
}
var message = response.data[i].message;
var
append =
"<div class='border'><div class='media'><div class='media-left media-middle'><a href='https://www.facebook.com/" + response.data[i].from.id + "' target='_blank'><img class='media-object' src='http://graph.facebook.com/" + response.data[i].from.id + "/picture?type=square'></a></div><div class='media-body' style='vertical-align: bottom'><a href='https://www.facebook.com/" + response.data[i].from.id + "' target='_blank'><h4 class='media-heading'>" + response.data[i].from.name + ".<br /><small>" + date + "</small></h4></a></div>";
if (message !== undefined) {
if (ValidURL(message) === 1) {
append +=
"<a class='ellipsis' href='" +
message +
"' target='_blank'>" +
message +
"</a>";
} else {
append += "<a class='ellipsis'>" + message + "</a>";
}
}
if (picture !== undefined)
append +=
"<a href='" +
response.data[i].link +
"' target='_blank'><img class='img-responsive' src='" +
picture +
"'/></a>";
if (description !== undefined)
append += "<p>" + description + "</p>";
append += '<hr///>' +
"<div class='btn-group btn-group-justified' role='group' aria-label='Justified button group'>" +
"<a href=" +
response.data[i].link +
" class='btn btn-default' role='button' target='_blank'><i class='fa fa-thumbs-up' aria-hidden='true'></i> Like</a>" +
"<a href=" +
response.data[i].link +
" class='btn btn-default' role='button' target='_blank'><i class='fa fa-comment' aria-hidden='true'></i> Comment</a></div></div></div>";
$("#facebook-group").append(append);
}
}
});
}
});
};
(function () {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
var formatDate = function (input) {
var d = new Date(Date.parse(input));
input = d.toString();
d = new Date(Date.parse(input.replace(/-/g, "/")));
var month = [
'january', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
];
var date = d.getDay().toString() +
" " +
month[d.getMonth().toString()] +
", " +
d.getFullYear().toString();
return (date);
};
function ValidURL(str) {
if (
/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(str))
return 1;
else
return -1;
}
</script>
Here formatDate & ValidURL are helper functions used for some cosmetic operations.

Bootstrap Select drop list moves down ward automatically

I am Bootstrap Select user in IE11.
When I fill data with ajax and open it then it automatically move down wards and when I select any value then it's not selected. How can I remove this error?
jQuery.ajax({
url: base_url + "UserBusinesses/ajaxState/" + countryId,
dataType: 'json',
beforeSend: function () {
$('#UserBusinessStateId').html('<option value="">Loding... </option>');
$('#UserBusinessStateId').selectpicker('refresh');
$('#UserBusinessCityId').html('<option value="">Select city</option>');
$('#UserBusinessCityId').selectpicker('refresh');
},
success: function (obj) {
var addHtml = '';
addHtml += '<option value="">Select state</option>';
$.each(obj, function (key, value) {
var selected = "";
if (selectedState == key) {
var selected = "selected='selected'";
}
addHtml += "<option value='" + key + "' " + selected + ">" + value + "</option>";
});
jQuery("#UserBusinessStateId").html(addHtml);
$('#UserBusinessStateId').selectpicker('refresh');
}
});
I am facing this issue In IE and I have find the solution
$('#UserBusinessStateId').selectpicker('refresh');
remove this and add this code
$('#UserBusinessStateId').selectpicker('render').selectpicker('refresh');

Web SQL results invalid order as i intended

I have 5 Questions in database table
1 textbox
2 dropdown
3 dropdown
4 textbox
5 textbox
but when I finish transactions it shows with invalid order like
1 textbox
4 textbox
5 textbox
then
2 dropdown
3 dropdown
it should be shown as above with correct order
in getDropdown function to get all options item
what's i'm doing wrong, Anyone can help? please,
//main function initially call to get all question
function showQuestions(){
db.transaction(function(tx) {
tx.executeSql(selectAllStatement, [], function(tx, result) {
dataset = result.rows;
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
if(item['ANS_TYPE'] == "dropdown"){
getDropdown(item['QU_MESSAGE'],item['QU_ID']);
}
if(item['ANS_TYPE'] == "textbox"){
getTextbox(item['QU_MESSAGE']);
}
}//for loop
});//execute
});//transaction
}//end function
function getTextbox(question){
$('#elements').append('<div data-role="fieldcontain">'
+ '<label for="textinput1">'
+ question
+ '</label><br /><br />'
+ '<input name="" id="textinput1" placeholder="" value="" type="text">'
+ '<br /><br /><hr></div>').trigger('create');
}
function getDropdown(question,qu_id){
var options = ''; option = '';
options += '<div data-role="fieldcontain">'
+ '<label for="selectmenu1">'
+ question
+ '</label><br /><br />';
db.transaction(function(tx) {
tx.executeSql(selectChoiceStatement, [qu_id], function(tx, result) {
dataset = result.rows;
option = '';
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
var data = item['CH_MSG'];
option += '<option>'+data+'</option>';
}
options += '<select id="selectmenu1" name="">'+option+'</select>'
+ '<br /><br /><hr></div>';
$('#elements').append(options).trigger('create');
});
});
}
The callback function of executeSql is called asynchronously.
You should probably create the <select> immediately and add the <option>s later.

Resources