sample angularjs code which will connects to sqllite - angularjs

kindly provide a sample code/link/tutorial which will connect to sqllite database from anugular js.
I am new mobile development
Basically when i am calling retriveProfileInfo function which is present in DataAccess.js
retriveProfileInfo function is executing in different thread i wanted in synchronous way.
Controller.js
mympn.controller('MyProfileController', function($scope, $location, ngDialog ) {
$scope.myProfileData = {};
$scope.myProfileDatalist = [];
function callBack(d) {
return d;
}
$scope.myProfileDatalist = retriveProfileInfo(callBack);
alert(myProfileDatalist);
console
.log("After calling retriveProfileInfo ----------------");
});
DataAccess.js
function retriveProfileInfo(callBack) {
var db = DataBaseInstance.getInstance();
var userProfileData = [];
db.transaction(function(tx) {
tx.executeSql("SELECT * from myprofile", [], function(tx, res) {
for (var i = 0; i < res.rows.length; i++) {
userProfileData[i] = res.rows.item(i);
}
});
}, errorCB, sucessCB);
console.log(userProfileData);
return callBack(userProfileData);
}

Related

master detail in ionic using json data

I'm using ionic v1 and trying to create list and its own detail, but when I click on the item list the detail view doesn't display the data of the item selected.
Factory
.factory('Eventos', function($http){
var eventos = [];
return {
all : function() {
return $http.get("eventos.json").then(function(response) {
eventos = response;
return eventos;
});
},
get : function(eventoId) {
for(i = 0; i < eventos.length; i++) {
if(eventos[i].id === eventoId){
return eventos[i];
}
}
return null;
}
}});
Controller
.controller('EventosCtrl', function($scope, $stateParams, Eventos) {
Eventos.all().then(function(eventos) {
$scope.eventos = eventos.data;
});
})
.controller('EventoCtrl', function($scope, $stateParams, Eventos) {
$scope.evento = Eventos.get($stateParams.eventoId);
}
But if I use the data static in the code this works, but I don't know whats wrong here.
If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues.
Many browsers don't allow locally hosted files to access other locally hosted files.
Try referencing your data as an object
var obj = {list:null};
$http.get('data.json').success(function(data) {
// you can do some processing here
obj.list = data;
});
return obj;

Integration of power bi reports with angular js in mvc application

How we can integrate power BI report with angular JS in mvc existing application. AS of now I am facing issue to display power bi report on angular view.
The way to go is: Use PowerBI Embedded (https://azure.microsoft.com/en-us/services/power-bi-embedded/)
I'm not an angular expert, but there is a Github repo aimed at this: https://github.com/Microsoft/PowerBI-Angular
Check out http://plnkr.co/edit/tQc1DF?p=info for a basic example of embedding a powerbi report and doing page navigation, using angular 1.4.x
var app = angular.module('plunker', [
'powerbi'
]);
app.controller('MainCtrl', function($scope, $http, models, PowerBiService) {
var staticReportUrl = 'https://powerbiembedapi.azurewebsites.net/api/reports/c52af8ab-0468-4165-92af-dc39858d66ad';
var _filterPaneEnabled = false;
var _navContentPaneEnabled = false;
var _reportHandle = null;
$scope.tree = [];
$http.get(staticReportUrl)
.then(function(responce) {
//create the config for the directive
var config = angular.extend(responce.data, {
settings: {
filterPaneEnabled: _filterPaneEnabled,
navContentPaneEnabled: _navContentPaneEnabled
}
});
$scope.embedConfiguration = config;
//create the nav-tree
$scope.tree.push(new models.Node(responce.data));
}, function(reason) {
});
$scope.onEmbedded = function(report) {
// get a reference to report object
_reportHandle = report;
//attach to events
report.on('loaded', OnloadedReport);
report.on('error', OnErrorReport);
};
function OnloadedReport(c) {
//get available pages to attach to navigation tree
_reportHandle.getPages()
.then(function(pages) {
pages.forEach(function(page) {
$scope.$apply(function() {
//populate the nav-tree
$scope.tree[0].pages.push(new models.Leaf(page));
});
});
})
.catch(function(error) {
console.log(error);
});
}
function OnErrorReport(e) {
console.log(e);
}
$scope.toggleFilterPaneClicked = function() {
_filterPaneEnabled = !_filterPaneEnabled;
_reportHandle.updateSettings({
filterPaneEnabled: _filterPaneEnabled
});
};
$scope.toggleNavContentPaneClicked = function() {
_navContentPaneEnabled = !_navContentPaneEnabled;
_reportHandle.updateSettings({
navContentPaneEnabled: _navContentPaneEnabled
});
};
$scope.setPage = function(page) {
_reportHandle.setPage(page.name);
};
$scope.fullScreen = function() {
_reportHandle.fullscreen();
};
});
app.factory('models', function() {
var Node = function(dataset) {
var self = this;
self.id = dataset.id;
self.name = dataset.name;
self.type = dataset.type;
self.accessToken = dataset.accessToken;
self.embedUrl = dataset.embedUrl;
self.webUrl = dataset.webUrl;
self.pages = [];
return self;
};
var Leaf = function(page) {
var self = this;
self.name = page.name;
self.displayName = page.displayName;
return self;
};
return {
Node: Node,
Leaf: Leaf
};
})
[1]https://microsoft.github.io/PowerBI-JavaScript/demo/static.html

Firebase child_removed not working in real-time

I am following tutsplus Real time web apps with Angularjs and Firebase.
I have main.js (below) which allows me to add and change items in Firebase in real time with no refresh of the browser (in Chrome and Safari).
However when I delete a message from Firebase I have to refresh the browser for the message list to update - so not in real time. I can't see where the problem is.
/*global Firebase*/
'use strict';
/**
* #ngdoc function
* #name firebaseProjectApp.controller:MainCtrl
* #description
* # MainCtrl
* Controller of the firebaseProjectApp
*/
angular.module('firebaseProjectApp')
.controller('MainCtrl', function ($scope, $timeout) {
var rootRef = new Firebase('https://popping-inferno-9738.firebaseio.com/');
var messagesRef = rootRef.child('messages');
$scope.currentUser=null;
$scope.currentText=null;
$scope.messages=[];
messagesRef.on('child_added', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
console.log(snapshotVal);
$scope.messages.push({
text: snapshotVal.text,
user: snapshotVal.user,
name: snapshot.key()
});
});
});
messagesRef.on('child_changed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
function deleteMessageByName(name){
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
$scope.messages.splice(i, 1);
break;
}
}
}
function findMessageByName(name){
var messageFound = null;
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
messageFound = currentMessage;
break;
}
}
return messageFound;
}
$scope.sendMessage = function(){
var newMessage = {
user: $scope.currentUser,
text: $scope.currentText
};
messagesRef.push(newMessage);
};
});
The code that is invoked when a message is deleted from Firebase:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
This code never actually deletes the message from the HTML/DOM.
There is a convenient deleteMessageByName method to handle the deletion. So if you modify the above to this, it'll work:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
deleteMessageByName(snapshot.key());
});
});

AngularJS paging

I made AngularJS pagination with spring mvc It works well ,but the application get a large amount of data from database so the application is very slow when I get first page because it get all records,Can anyone help me to solve this problem?I want to get subset of data from database depending on angularJS pagination
Spring mvc Controlller
#RequestMapping(value = "/rest/contacts",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public List<Contact> getAll() {
return contactRepository.findAll();
}
AngularJS Service
pagingpocApp.factory('Contact', function ($resource) {
return $resource('app/rest/contacts/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': { method: 'GET'}
});
});
AngularJS Controller
pagingpocApp.controller('ContactController', function ($scope, $filter,resolvedContact, Contact, resolvedRole) {
$scope.contacts = resolvedContact;
var sortingOrder = 'firstName';
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 10;
$scope.pagedItems = [];
$scope.currentPage = 0;
var searchMatch = function (haystack, needle) {
if (!needle) {
return true;
}
return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
};
// init the filtered items
$scope.search = function () {
$scope.filteredItems = $filter('filter')($scope.contacts, function (item) {
for(var attr in item) {
if (searchMatch(item[attr], $scope.query))
return true;
}
return false;
});
// take care of the sorting order
if ($scope.sortingOrder !== '') {
$scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sortingOrder, $scope.reverse);
}
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
};
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
// functions have been describe process the data for display
$scope.search();
// change sorting order
$scope.sort_by = function(newSortingOrder) {
if ($scope.sortingOrder == newSortingOrder)
$scope.reverse = !$scope.reverse;
$scope.sortingOrder = newSortingOrder;
// icon setup
$('th i').each(function(){
// icon reset
$(this).removeClass().addClass('icon-sort');
});
if ($scope.reverse)
$('th.'+new_sorting_order+' i').removeClass().addClass('icon-chevron-up');
else
$('th.'+new_sorting_order+' i').removeClass().addClass('icon-chevron-down');
};
});
One quick option would be to create a get method on your API that only returns a subset of the data, maybe only 25 contacts at a time, or a page or two worth of data. Then you could create a service in angular that makes that get call every 3 seconds or so to get the next 25 contacts. A sort of lazy loading technique.
Ben Nadel does a great job in this article of outlining how his company handles large sets of images being loaded to a page using a lazy loading technique. Reading through his example could give you a nice starting point.
Edit: I'm also going to recommend you refer to this solution for an answer slightly more on point to what you're looking to achieve. He recommends pushing data to your controller as soon as it's found:
function MyCtrl($scope, $timeout, $q) {
var fetchOne = function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve([random(), random() + 100, random() + 200]);
}, random() * 5000);
return deferred.promise;
};
$scope.scans = [];
for (var i = 0; i < 2; i++) {
fetchOne().then(function(items) {
angular.forEach(items, function(item) {
$scope.scans.push(item);
});
});
};
}

Load data to dropdown in angularjs

I am new to this angular js.
In my code a dropdown control has been loaded with some items, i know this list should be loaded from a xml file.
I want to know where/how it is been coded to load the data. Check this code and help me...
<select size="10" ng-model="model.addSelection" ng-options="a.name for a in availableList | availableList | propertyFilter:model.availableFilter" class="listBoxStyle" wat-focus/>
angular.module('readbackSelectModule', [])
.filter('availableList', [
function () {
return function (input) {
if (!angular.isArray(input)) return input;
var out = [];
for (var i = 0; i < input.length; i++) {
if (input[i].visible == true)
out.push(input[i]);
}
return out;
}
}
])
.filter('plotList', [
function () {
return function (input) {
if (!angular.isArray(input)) return input;
var out = [];
for (var i = 0; i < input.length; i++) {
if (input[i].visible == false)
out.push(input[i]);
}
return out;
}
}
])
.controller('readbackSelectCtrl', ['$scope', '$modalInstance', 'generalDataService', 'keyService', 'propertyFilterFilter', 'availableListFilter', 'plotListFilter', 'plotPanelService',
function ($scope, $modalInstance, generalDataService, keyService, propertyFilterFilter, availableListFilter, plotListFilter, plotPanelService) {
var CANCEL_MESSAGE = 'cancel';
var GET_DATA_MESSAGE = 'getdata';
var REQUEST_PROPERTY_LIST_MESSAGE = 'requestplotdata';
var SUBSCRIBE = 'plotsubscribe';
var UNSUBSCRIBE = 'plotunsubscribe';
var STREAM_TYPE = '4';
$scope.model = {};
$scope.model.addSelection;
$scope.model.removeSelection;
$scope.model.availableFilter;
// List of properties
$scope.availableList = [];
};
Use Angular's $http service.
You can do it in your readbackSelectCtrl, like this:
...
$scope.model = {};
$scope.model.addSelection;
$scope.model.removeSelection;
$scope.model.availableFilter;
$http.get(/** insert XML file URL here **/)
.success(function(data) {
// process the data and extract the XML elements you want
$scope.availableList = xmlExtractedArray;
})
.error(function(err) {
// handle error
});
Check this plunker for a working demo.

Resources