Fetch and display data from database in AngularJs - javascript

How can I pop the list of my clients on the screen, the list is coming from my database, I have 11 rows of clients and I want to create a listview of those and show them, this is my code:
dbFactory.method = function findAll() {
db.transaction(
function(tx) {
var sql = "SELECT (nome) as nomes FROM clientes";
log(sql);
tx.executeSql(sql, [],
function(tx, results) {
var len = results.rows.length,
clientes = [],
i = 0;
for (; i < len; i = i + 1) {
clientes[i] = results.rows.item(i).nomes;
}
log(clientes + ' found');
}
);
},txErrorHandler,
function () {
}
);
};
Controller:
.controller('ListaCtrl', function ($scope, dbFactory) {
$scope.items = dbFactory.method();
console.log(dbFactory.method());
});
clientes.html:
<ion-view view-title="Playlists" ng-app="starter">
<ion-content>
<ion-list>
<ion-item ng-repeat="itens in items" >
<p>{{itens.nome}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
The log:
Promise {$$state: Object, then: function, catch: function, finally: function}
$$state: Object
status: 1
value: SQLResultSet
insertId: [Exception: DOMException: Failed to read the 'insertId' property from 'SQLResultSet': The query didn't result in any rows being added.]
rows: SQLResultSetRowList
length: 11
__proto__: SQLResultSetRowList
rowsAffected: 0

I've managed to solve that using deferred and promise, here is what I did:
var getMessages = function findAll() {
db.transaction(
function(tx) {
var sql = "SELECT (nome) as nomes FROM clientes";
tx.executeSql(sql, [],
function(tx, results) {
var len = results.rows.length,
clientes = [],
i = 0;
for (; i < len; i = i + 1) {
clientes[i] = results.rows.item(i).nomes;
}
log(clientes + ' rowsss found');
deferred.resolve(clientes);
}
);
},txErrorHandler,
function () { }
);
return deferred.promise;
};
return {
showClientes: getMessages
};
The Controller:
.controller('ListaCtrl', function ($scope, dbFactory) {
dbFactory.showClientes().then(function(listview) {
$scope.clientes = listview;
console.log($scope.clientes);
});
});
And the html:
<ion-view view-title="Playlists" ng-app="starter">
<ion-content>
<ion-list>
<ion-item ng-repeat="cliente in clientes">
{{cliente}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Now I can see my listview with all my clients.

.controller('ListaCtrl', function ($scope, dbFactory) {
dbFactory.method().$promise.then(
function(res){
$scope.items = res; //or res.data
},
function(){
//error call back
}
);
});

Related

ng-repeat doesn´t load after ng-click

i´ve got an problem with my ng-repeat.
After clicking ng-click, my ng-repeat doesn´t load, the page is empty. I´ve got an html file calls "food.html" in which i call the ng-click() further i´ve got an "food-snack.html" file which contains the ng-repeat and at least my "controller.js" where the function of ng-click is calling. I hope someone can help me. Im sorry for my confusing notation but it´s my first blog.
1.food-snack.html
<ion-content class="padding" >
<ion-refresher pulling-text="Refresh" on-refresh="refreshAll('snack')"></ion-refresher>
<ion-checkbox class = "item-checkbox-right checkbox-dark" ng-repeat="food in snacks">
<h2><b>{{food.food}} </b></h2>
<p>Preis: {{food.price}} {{food.currency}}</p>
</ion-checkbox>
</ion-content>
2.food.html
<ion-content class="padding">
<br><br><br><br><br><br><br>
<button class = "button button-block button-dark" ng-click = "getSnacks()" > Snacks </button>
<button class = "button button-block button-dark" ng-click = "getSandwich()" > Sandwich </button>
</ion-content>
3.controller.js
.controller('TablesCtrl', function($scope, $stateParams, $ionicPopup, $http, $state, $timeout, Foods) {
$scope.getSnacks = function(){
$state.go("tab.food-snack");
$http.get('http://xxxxxx/connect.php?getSnacks=1').then(function successCallback(response)
{
$scope.snacks = Foods.appendAll(response.data);
console.log(response);
}, function errorCallback(response) {
var confirmPopup = $ionicPopup.confirm({
title: 'Nicht erfolgreich',
cancelText: 'Nein',
okText: 'Ja',
okType: 'button-dark',
cancelType: 'button-positive'
});
});
};//END OF FUNCTION getSnacks()
$scope.getSandwich = function ()
{
$state.go("tab.food-sandwich");
$http.get('http://xxxxxx/connect.php?getSandwich=1').then(function successCallback(response)
{
$scope.sandwich = Foods.appendAll(response.data);
console.log(response);
}, function errorCallback(response) {
var confirmPopup = $ionicPopup.confirm({
title: 'Nicht erfolgreich',
cancelText: 'Nein',
okText: 'Ja',
okType: 'button-dark',
cancelType: 'button-positive'
});
});
}// END OF FUNCTION $scope.getSanwich()
4. app.js
.state('tab.foods', {
cache: false,
url: '/addTable/foods',
views: {
'tab-tables': {
templateUrl: 'templates/foods.html',
controller: 'TablesCtrl'
}
}
})
.state('tab.food-snack', {
cache: false,
url: '/addTable/foods/food-snack',
views: {
'tab-tables': {
templateUrl: 'templates/food-snack.html',
controller: 'TablesCtrl'
}
}
})
5.services.js
.factory('Foods', function() {
var foods = [];
return {
appendAll: function(array) {
for(var i = 0 ; i < array.length; i++)
{
foods.splice(array[i]);
}
for (var i = 0; i < array.length; i++)
{
foods.unshift(array[i]);
}
return foods;
},
getAll: function() {
return foods;
},
remove: function(food) {
foods.splice(foods.indexOf(food), 1);
},
removeAll: function(array) {
for( var i = 0 ; i < array.length; i++)
{
foods.splice(array[i]);
}
},
get: function(foodId) {
for (var i = 0; i < foods.length; i++) {
if (foods[i].id === parseInt(foodId)) {
return foods[i];
}
}
return null;
}
The controller you shared is the controller of the food. html I guess and it is adding the snack list to it's scope which is not the scope of snack.html. In the food controller just change the state and in the controller of snacks call the service to get the snacks.

How to load dynamic column and rows by Using ag-grid?

Html Code :
<div class="panel-body" style="padding-bottom:0px">
<div id="myGrid" ag-grid="gridOptions" class="ag-fresh" style="height: 100%;"></div>
</div>
Angular Code :
var sqdtApp = angular.module("sqdtApp", ['ngTouch',
'ui.grid', 'ui.grid.pagination', 'ui.grid.resizeColumns',
'angularUtils.directives.dirPagination', 'ngAnimate', 'ui.bootstrap', 'agGrid']);
sqdtApp.controller(
'importedtableCtrl',
function ($http, $scope, $stateParams,$rootScope, $httpParamSerializer, uiGridConstants) {
$scope.dbtype = $stateParams.dbname;
$scope.columns = [];
$scope.gridOptions = {
columnDefs: [],
enableFilter: true,
rowData: [],
rowSelection: 'multiple',
rowDeselection: true
};
$scope.customColumns = [];
$http.post($scope.url + "/importedtablesCount", { 'dbname': $stateParams.dbname })
.success(
function (result) {
$scope.importedTableCount = result;
});
var gridtablename = "";
$scope.currentImportedTableName = '';
$scope.loadTableInGrid = function (tablename) {
$scope.currentImportedTableName = tablename;
if (gridtablename != tablename) {
$scope.reset();
gridpageno = 1;
$http.post($scope.url + "/getPagingRecordImportedTable", { 'dbname': $stateParams.dbname, 'tableName': tablename, 'pageNumber': 1 }).success(
function (response) {
$scope.names = response.records;
$scope.mdata = response.metadata;
// $scope.gridOptions.data = response.records;
var columnsize = 0;
console.log($scope.customColumns);
for (var obj in $scope.mdata) {
if ($scope.mdata[obj]['columnsize'] > 20) {
columnsize = 20;
} else {
columnsize = $scope.mdata[obj]['columnsize'];
}
$scope.customColumns.push({
headerName: $scope.mdata[obj]['columnname'],
field: $scope.mdata[obj]['columnname'],
headerClass: 'grid-halign-left'
});
}
$scope.gridOptions.columnDefs = $scope.customColumns;
$scope.gridOptions.rowData = $scope.names;
gridtablename = tablename;
gridpageno = 1;
$scope.getTotalNoOfRecordCountForGrid(tablename);
}).error(function (data) {
alert(data);
});
} else {
$scope.reset();
$scope.resetGridTableName();
}
};
});
Output No Rows to Show
no rows to show is output
but if i check in $scope.gridoptions object all the rows and column are there.
$scope.gridOptions object in console with data
but it not rendering in page.
help me out.
$scope.gridOptions.columnDefs = $scope.customColumns;
$scope.gridOptions.rowData = $scope.names;
Those are very likely the culprits : columnsDefs and rowData are only for grid initialisation before the ready event.
Use gridOptions.api.setColumnDefs and gridOptions.api.setRowData to interact with the grid once it's initialized
Documentation : https://www.ag-grid.com/angular-grid-api/index.php

$scope value is null in DOM

I am attempting to use ng-repeat with AngularJS but I am not getting the result of my scope in my DOM. Can anyone see the issue? I have been trying to troubleshoot this for hours and hours now and "players" is always null.
Here is my html:
<body ng-controller="CoachCtrl" >
<div class="mdl-tabs mdl-js-tabs mdl-js-ripple-effect">
<div class="mdl-tabs__tab-bar">
Starks
Lannisters
Targaryens
</div>
<div class="mdl-tabs__panel is-active" id="coach" >
<p>Number of players {{ players.length }}</p>
<table class="table">
<tr>
<th>Firstname
</th>
<th>Lastname
</th>
<th>Tryout Date
</th>
</tr>
<tr ng-repeat="kid in players" >
<td>{{ kid.firstname }}
</td>
<td>{{ kid.lastname }}
</td>
<td>{{ kid.tryout_date }}
</td>
</tr>
</table>
</div>
</div>
and here is my js:
'use strict';
angular.module('myApp.coach', ['ngRoute', 'firebase'])
// Declared route
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/coach', {
templateUrl: 'coach/coach.html',
controller: 'CoachCtrl'
});
}])
// Home controller
.controller("CoachCtrl", ["$scope", "$firebaseAuth", "$location",
function($scope, $firebaseAuth, $location) {
var ref = new Firebase("https://intense-heat-2545.firebaseio.com");
var authData = ref.getAuth();
if(authData){
console.log("User is "+authData.uid+" and is logged in with "+authData.provider);
var league = new Firebase("https://intense-heat-2545.firebaseio.com/users/"+authData.uid+"/league");
league.on("value", function(snapshot){
console.log("League ID = "+snapshot.val());
var leagueVal = snapshot.val();
var playerlist = new Firebase("https://blahblah.firebaseio.com/"+leagueVal+"/players");
$scope.players = [];
$scope.players.push({firstname:'John', lastname:'B', tryout_date:'2015-11-30'});
$scope.players.push({firstname: 'Marty', lastname: 'B', tryout_date: '2015-12-01'});
playerlist.on("child_added", function(snapshot){
//console.log("players ="+snapshot.val());
var player = snapshot.val();
console.log("Firstname ="+player.firstname);
var first = player.firstname;
var last = player.lastname;
var tyd = player.tryout_date;
console.log('player data ='+first+last+tyd);
$scope.players.push({ firstname: first, lastname: last, tryout_date: tyd });
var len = $scope.players.length;
for (var i = 0; i < len; i+=1){
if (1 === len){
console.log("player name = "+$scope.players[i].firstname);
}
}
console.log("players len ="+$scope.players.length);
}, function(error){
console.log("Error getting player info: "+error.code);
});
console.log("players ="+$scope.players[1].firstname+" len= "+$scope.players.length);
}, function(error){
console.log("Erro ="+error.code);
});
} else {
console.log("User is not logged in.");
$location.path('/signin');
}
}
]);
Three things.
The with the regular Firebase SDK Angular doesn't know when to run $digest.
Use $firebaseArray() rather than manipulating your own.
Use resolve() in the router to inject the user with $firebaseAuth().$waitForAuth().
-
var rootRef = new Firebase("https://<my-firebase-app>.firebaseio.com");
var leagueRef = rootRef.child("users").child(authData.uid).child("league");
// read it one time
leagueRef.once('value', function(snap) {
var leagueVal = snapshot.val();
var playerList = rootRef.child(leagueVal).child("players");
// $firebaseArray() will synchronize child events into an array
// Each update will know how to update $digest as well, which
// will keep the view updated.
$scope.players = $firebaseArray(playerList);
});
Your controller code would be greatly simplified if you use resolve in the router.
.constant('FBURL', '<my-firebase-app>')
.service('RootRef', ['FBURL', Firebase)
.factory('Auth', function($firebaseAuth, RootRef) {
return $firebaseAuth(RootRef);
})
.factory('UserLeague', function(RootRef) {
return function(uid) {
var leagueRef = RootRef.child("user").child(uid).child("league");
var deferred = $q.defer();
leagueRef.once(function(snap) {
deferred.resolve(snap.val());
});
return deferred.promise;
}
})
.config(function($routeProvider) {
$routeProvider.when('/coach', {
templateUrl: 'coach/coach.html',
controller: 'CoachCtrl',
resolve: {
leagueVal: function(UserLeague, Auth) {
var authData = Auth.$getUser();
return UserLeague(authData.uid);
},
authData: function(Auth) {
return Auth.$waitForAuth();
}
}
});
})
.controller("CoachCtrl", function($scope, leagueVal, authData, RootRef) {
// no need to check for a user because authData is injected
// use the resolved leagueVal to create a ref
var playerList = RootRef.child(leagueVal).child("players");
// synchronize the players to an array
$scope.players = $firebaseArray(playerList);
});

Ionic Framework with External JSON File

i have a problem that i don't know how to solve, i have an IONIC Tabs Template and want to add an external JSON File to be showing instead of the template friends list that appears by default.
This is my app.js file
.state('tab.friends', {
url: '/friends',
views: {
'tab-friends': {
templateUrl: 'templates/tab-friends.html',
controller: 'FriendsCtrl'
}
}
})
.state('tab.friend-detail', {
url: '/friends/:friendId',
views: {
'tab-friends': {
templateUrl: 'templates/friend-detail.html',
controller: 'FriendDetailCtrl'
}
}
})
This is my controllers.js file
.controller('FriendsCtrl', function($scope, Friends) {
$scope.friends = Friends.all();
})
.controller('FriendDetailCtrl', function($scope, $stateParams, Friends) {
$scope.friend = Friends.get($stateParams.friendId);
})
This is my services.js file, that access a JSON file:
.factory('Friends', function($http) {
var friends = [];
return {
all: function(){
return $http.get("http://yanupla.com/apps/ligajaguares/equipos.json").then(function(response){
friends = response.data;
console.log(friends);
return friends;
});
},
get: function(friendId) {
for (var i = 0; i < friends.length; i++) {
if (friends[i].id === parseInt(friendId)) {
return friends[i];
}
}
return null;
}
}
});
And finally my tabs-friends.hm template:
<ion-view view-title="Friends">
<ion-content>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="friend in friends" type="item-text-wrap" href="#/tab/friends/{{friend.id}}">
<!--img ng-src="{{chat.face}}"-->
<h2>{{friend.name}}</h2>
<p>{{friend.bio}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
I can see the JSON file object in my browser using console.log, but i can't see anything else in the body of my template only the "Friends" title.
What 'm missing here?
I would guess that angular is accessing $scope.friends while it is still a promise. Have you tried resolving the variable by using the resolve statement in the .state-definition?
app.js should look something like this:
.state('tab.friends', {
url: '/friends',
views: {
'tab-friends': {
templateUrl: 'templates/tab-friends.html',
controller: 'FriendsCtrl',
resolve: {
allfriends: function(Friends) {
return Friends.all(); }
}
}
}
})
and the controller would be:
.controller('FriendsCtrl', function($scope, allfriends) {
$scope.friends = allfriends;
})
I think you need to use $q for correctly resolving, so the Service needs to look like this:
.factory('Friends', function($http, $q) {
var friends = [];
return {
all: function(){
var dfd = $q.defer();
$http.get("http://yanupla.com/apps/ligajaguares/equipos.json").then(function(response){
friends = response.data;
console.log(friends);
dfd.resolve(friends);
});
return dfd.promise;
},
get: function(friendId) {
for (var i = 0; i < friends.length; i++) {
if (friends[i].id === parseInt(friendId)) {
return friends[i];
}
}
return null;
}
}
});
For more information on this, i recommend reading this formula from ionic: http://learn.ionicframework.com/formulas/data-the-right-way/
Additionally, this helped me a great deal in understanding the concept of promises:
http://andyshora.com/promises-angularjs-explained-as-cartoon.html

angularjs restricting count to current scope

I am tring to setup a counter where for each country in my list I can keep count of how many clicks there has been plus an overall tally.
I have the below so far which can be viewd in this fiddle. The issue I am having is that I am not able to keep the count unique for each country. How can this be achieved?
<div ng-app="myApp">
<div data-ng-view></div>
</div>
'use strict';
var myApp = angular.module('myApp', ['ngRoute', 'templates/view1.html', 'templates/view2.html']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryListCtrl'
})
.when('/:id', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
})
}]);
myApp.factory('Countries', ['$q', function ($q) {
var countriesList = [];
// perform the ajax call (this is a mock)
var getCountriesList = function () {
// Mock return json
var contriesListMock = [
{
"id": "0",
"name": "portugal",
"abbrev": "pt"
}, {
"id": "1",
"name": "spain",
"abbrev": "esp"
}, {
"id": "2",
"name": "angola",
"abbrev": "an"
}
];
var deferred = $q.defer();
if (countriesList.length == 0) {
setTimeout(function () {
deferred.resolve(contriesListMock, 200, '');
countriesList = contriesListMock;
}, 1000);
} else {
deferred.resolve(countriesList, 200, '');
}
return deferred.promise;
}
var getCountry = function(id) {
var deferred = $q.defer();
if (countriesList.length == 0) {
getCountriesList().then(
function() {
deferred.resolve(countriesList[id], 200, '');
},
function() {
deferred.reject('failed to load countries', 400, '');
}
);
} else {
deferred.resolve(countriesList[id], 200, '');
}
return deferred.promise;
}
var cnt = 0;
var cntryCnt = 0;
var incCount = function() {
cnt++;
return cnt;
}
var incCntryCount = function(id) {
cntryCnt++;
return cntryCnt;
}
return {
getList: getCountriesList,
getCountry: getCountry,
getCount : function () {
return cnt;
},
getCntryCount : function () {
return cntryCnt;
},
incCount: incCount,
incCntryCount: incCntryCount
};
}]);
myApp.controller('CountryListCtrl', ['$scope', 'Countries', function ($scope, Countries) {
$scope.title = '';
$scope.countries = [];
$scope.status = '';
Countries.getList().then(
function (data, status, headers) { //success
$scope.countries = data;
},
function (data, status, headers) { //error
$scope.status = 'Unable to load data:';
}
);
}]);
myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries', function ($scope, $routeParams, Countries) {
$scope.country = {
id: '',
name: '',
abbrev: ''
};
var id = $routeParams.id;
Countries.getCountry(id).then(
function(data, status, hd) {
console.log(data);
$scope.country = data;
$scope.countOverall = Countries.getCount;
$scope.countCntry = Countries.getCntryCount;
$scope.clickCnt = function () {
$scope.countTotal = Countries.incCount();
$scope.country.clicks = Countries.incCntryCount(id);
console.log($scope);
};
},
function(data, status, hd) {
console.log(data);
}
);
}]);
angular.module('templates/view1.html', []).run(["$templateCache", function ($templateCache) {
var tpl = '<h1>{{ title }}</h1><ul><li ng-repeat="country in countries"><a href="#{{country.id}}">{{country.name}}</div></li></ul>';
$templateCache.put('templates/view1.html', tpl);
}]);
angular.module('templates/view2.html', []).run(["$templateCache", function ($templateCache) {
var tpl = '<div>{{country.name}} clicks {{countCntry()}} <br> overall clicks {{countOverall()}}</div><button>BACK</button><button ng-click="clickCnt()" >count clicks ++ </button>';
$templateCache.put('templates/view2.html', tpl);
}]);
The problem is that you are not incrementing a count based on the country. Working on the fiddle right now.
EDIT:
I've updated the fiddle: http://jsfiddle.net/1xtc0zhu/2/
What I basically did was making the cntryCnt an object literal which takes the country id as a property and keeps the right counting per each id, like so:'
var cnt = 0;
var cntryCnt = {};
...
// The function now receives the country id and increments the specific country clicks only.
var incCntryCount = function(id) {
cntryCnt[id] = cntryCnt[id] || 0;
cntryCnt[id]++;
return cntryCnt[id];
}
The rest of the changes are in the templates, and are basically only sending the country id as a param when getting or incrementing the counts.
Also, this is not an Angular Specific question, but more a programming in general question.

Categories

Resources