Do a loop instead of multiple $http chaining? - angularjs

sorry, i have checked answers, but still dont understand how to make it :
I've got an array :
var surfaces = [
{min:0,max:499},
{min:500,max:999},
{min:1000,max:1499},
{min:1500,max:1999},
{min:2000,max:2399},
{min:2400,max:2999},
{min:3000,max:3999},
{min:4000,max:5999},
{min:6000,max:100000}
]
And I've got this looong $http chained calls with $q :
$q.when()
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[0]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[1]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[2]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[3]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[4]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[5]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[6]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[7]).success(function(data){
$scope.normes.push(data);
})
})
.then(function () {
$http.post('backend/backend.php?action=get_normes',surfaces[8]).success(function(data){
$scope.normes.push(data);
})
})
I'd rather do a loop, but have now idea on how to do this !!
EDIT : I've got way bigger problem : data is not in order in $scope.normes ! Its always different ! How could i do to always push in order ? How could the data could be in order ?
I got ng-repeats like this but the information is not well ordered because of $http synchornicity ;
<div class="row ">
<div class="col-lg-10" style="overflow: auto; max-height: 600px;">
<table class="table table-bordered table-hover " border="1" >
<thead >
<tr>
<th> Désignation</th>
<th> Total Magasins</th>
<th> Moy Habitants Zone</th>
<th> Ca Moyen</th>
<th> EO Mini</th>
<th> EO Maxi</th>
<th> Coef Moyen</th>
<th> Pourcent Côtier</th>
<th> Pourcent Urbain</th>
<th> Tx Habituels</th>
<th> Tx fréquentation</th>
<th> Tx fidélisation</th>
<th> Zone Attraction</th>
<th> Revenus Zone</th>
<th> Nb Perso Foyer</th>
<th> Age Moyen</th>
</tr>
</thead>
<tbody >
<tr ng-repeat="norme in normes" >
<td>Surface 0-499 m²</td>
<td>{{::norme.nb_magasins | number:0}}</td>
<td>{{::norme.moy_habitants_zone | number:0}}</td>
<td>{{::norme.ca_moyen | number:0}}</td>
<td>{{::norme.eomin | number:0}}</td>
<td>{{::norme.eomax | number:0}}</td>
<td>{{::norme.coef_moyen | number:2}}</td>
<td></td>
<td></td>
<td>{{::norme.tx_habituels | number:2}}</td>
<td>{{::norme.tx_frequentation | number:2}}</td>
<td>{{::norme.tx_fidelisation | number:2}}</td>
<td>{{::norme.attraction | number:0}}</td>
<td>{{::norme.revenus_zone | number:0}}</td>
<td>{{::norme.nb_pers_foyer | number:2}}</td>
<td>{{::norme.age_moyen | number:2}}</td>
<td ></td>
</tr>
</tbody>
</table>
</div>
Each time i redo the $q, it comes with a different order ! How could i do ?
EDIT : So I'm now getting standards JSON objects from the Back End so it is simplier(Editied the html table on this post), but with the solutions you gently provided, it doesnt appear yet in the right order. The $http get started in the right order, but it seems that $scope.normes doesnt list as the $http have been started ! (Oh i think i maybe can order with the orderby in the front end... I forgot, but i thought it was possible to order the json objects as they get pushed into the array, but in the view it doesnt appear as when the $http have been called)

Try this::
$scope.onAllDone = function() {
var promises = [];
angular.forEach(surfaces , function(surface) {
promises.push($http.post('backend/backend.php?action=get_normes',surface)).then(function(data) {
$scope.normes.push(data);
return data;
});
});
return $q.all(promises);
}
USE::
$scope.onAllDone().then(fnSuccess, fnError);

Promises and $q.all (doc) are your friends.
In more detail, you will have to make a promise for each call (if the call itself does not return one), push them in an array and call $q.all(promises).then(allFinished).
function callUpdate(x, promises) {
var d = $q.defer();
$http.post('backend/backend.php?action=get_normes',x).then(function(resp){
$scope.normes.push(resp.data);
d.resolve(resp.data);
})
promises.push(d.promise);
}
...
var promises = [];
$scope.normes = [];
for (var i = 0; i < surfaces.length; i++) {
callUpdate(surfaces[i], promises);
}
$q.all(promises).then(function() {
// called when all promises have been resolved successully
});

Create an array of promises
var promises = [];
surfaces.forEach(function(surface){
promises.push($http.post('backend/backend.php?action=get_normes',surface));
})
You can use $q.all() and wait for all promises to complete and use Array.concat() to create $scope.normes array.
$q.all(promises).then(function (results) {
$scope.normes = [].concat.apply([],results);
});

When chaining promises, it is important to return the subsequent promise to the .then method handler function:
var arrayPromise = $q.when([])
.then(function (dArray) {
var httpPromise = $http.post('backend/backend.php/action=get_normes',surfaces[0])
var dPromise = httpPromise.then(function(response) {
$scope.normes.push(response.data);
dArray.push(response.data);
return dArray;
});
return dPromise;
}).then(function(dArray) {
console.log("one XHR is complete");
console.log(dArray);
});
When the code fails to return anything to the handler function, the $q service resolves the promise as undefined and immediately executes the next function. By returning the subsequent promise, the $q service will wait for the promise to resolve before executing the next promise in the chain.
That said. How to create a loop that chains sequential promises?
var arrayPromise = $q.when([]);
for (let n=0; n<surfaces.length; i++) {
arrayPromise = arrayPromise
.then(function (dArray) {
var httpPromise = $http.post(url,surfaces[n]);
var dPromise = httpPromise.then(function(response) {
$scope.normes.push(response.data);
dArray.push(response.data);
//return dArray to chain
return dArray;
});
return dPromise;
});
};
arrayPromise.then(function(dArray) {
console.log("all XHRs are complete");
console.log(dArray);
}).catch(function(errorResponse) {
console.log("one of the XHRs failed");
console.log(errorResponse.status);
throw errorResponse;
});
Create a variable with a promise for an empty array. Then in the loop simply assign the promise derived from the .then method back to that variable. Each iteration of the loop returns an array that is one item larger than the previous iteration. Also each iteration has the side effect of pushing an item to scope.

Related

Unable to bind Json Data with Table Header using AngularJS

Im getting data in this format from api, but when i try binding it to table using angularjs it is creating empty space instead of values. Im also getting more then one table from some Api's please explain who to bind different datatables in different tables too. thanks
{"Table":
[{
"SchoolId":1,
"schoolname":"Microsoft",
"SCHOOLCODE":"29911583",
"WEBSITE":"JLR",
"USEREMAIL":"faucibus#aliquamiaculislacus.org",
"PHONE":"841-9331",
"ADDRESS1":"682-5760 Felis Street",
"ISACTIVE":0,
"PLANTYPE":3
}]
}
Angular Controller
SMSApp.factory('GetStudentService', function ($http) {
studobj = {};
studobj.getAll = function () {
var stud=[];
stud = $http({ method: 'Get', url: 'http://localhost:58545/api/Student?Studentid=1' }).
then(function (response) {
return response.data;
});
return stud;
};
return studobj;
});
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result;
console.log(result);
});
});
HTML Code
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
WHAT I GET
Change in your Angular Controller :
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
/********************* Changed Here ********************/
$scope.school = JSON.parse(result._body); // Or only JSON.parse(result)
$scope.school = $scope.school.table;
});
});
And your HTML Code :
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
Naming the data school is confusing. Do instead:
GetStudentService.getAll().then(function (data) {
$scope.tableObj = data;
console.log(data);
});
<tbody ng-controller="studentController">
<tr ng-repeat="school in tableObj.Table track by school.SchoolId">
<td>{{school.SchoolId}}</td>
<td>{{school.schoolname}}</td>
<td>{{school.SCHOOLCODE}}</td>
<td>{{school.WEBSITE}}</td>
<td>{{school.USEREMAIL}}</td>
</tr>
</tbody>
From the Docs:
Best Practice: If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance, e.g. item in items track by item.id. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.
— AngularJS ng-repeat API Reference
Just replace your result with result.Table in your controller because if you properly see your response it is inside "Table" named array. Try this you should be able to see your records
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result.Table;
console.log(result);
});
});
Note: I have replaced your API call in the jsfiddle link with the response mentioned in the question.
JSFiddle Link : http://jsfiddle.net/zu8q7go6/9/

How to echo JSON array as Smart Table data with Angluarjs

I'm pretty new to Angular, and trying to build a table using Smart Table based on data I'm fetching from a REST api. I can build the table fine with manually entered data, but when I try to insert a JSON array of data from the server the resulting table is empty.
Currently I have the following set up:
dataFactory.js - calls the API and gets a JSON response:
app.factory('dataFactory', ['$http', function($http) {
var urlBase = 'http://myurl.com/api';
var dataFactory = {};
dataFactory.getOrders = function() {
return $http.get(urlBase + '/orders');
};
return dataFactory;
}]);
My view is fairly basic and looks like this using to the Smart Table extension:
<div ng-controller="MainController">
<table st-table="ordersTable" class="table table-striped">
<thead>
<tr>
<th st-sort="createdBy">Name</th>
<th st-sort="id">ID</th>
<th st-sort="state">State</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in ordersTable">
<td>{{row.createdBy}}</td>
<td>{{row.id}}</td>
<td>{{row.state}}</td>
</tr>
</tbody>
</table>
</div>
And my MainController.js processes and stores the data, and builds the table:
app.controller('MainController', ['$scope', 'dataFactory', function($scope, dataFactory) {
$scope.status;
$scope.orders;
getOrders();
function getOrders() {
dataFactory.getOrders()
.success(function(ord) {
$scope.orders = ord;
})
.error(function(error) {
$scope.status = 'Unable to load order data: ' + error.message;
});
}
$scope.ordersTable = [
// If I build the data manually the table builds using the following 3 lines
//{createdBy: 'Laurent', id: '56433', state: 'Open')},
//{createdBy: 'Blandine', id: '34367', state: 'Open')},
//{createdBy: 'Francoise', id: '34566', state: 'Closed'}
//... however I actually want the data to come from the JSON array returned by my factory like this:
$scope.orders
];
}]);
What am I doing wrong? How can I get my data to show up in the table?
In the success callback you are updating $scope.orders and not $scope.orderTable. By the way use promise function then instead of success and error callback (extract from angularjs doc):
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

ngTable don't updated after add new data

my problem is if I add new item to the database the ngTable don't updated with new data automatically but if I refresh the page (f5) the data is shown.
I use ng table to show data.
PS: the AngularJS consume data from JSON produced by restful WS from a JEE backend connected to a dataBase.
the ng-table :
<table ng-table="tablePy" show-filter="true"
class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th> Code </th>
<th> Libellé</th>
<th>Code Alphabetique 2</th>
<th>Code Alphabetique 3</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat=" py in paysValues | filter:searchValeur ">
<td align="right"> {{py.codPay}}</td>
<td > {{py.libPay}}</td>
<td> {{py.codAlph2}}</td>
<td> {{py.codAlph3}}</td>
</tr>
</tbody>
</table>
the function that fill the table is :
var initPaysData = function () {
var promise =
allPaysService.getPays();
promise.then(
function (res) {
$scope.paysValues = res.data;
$scope.tablePy = new NgTableParams({}, {dataset: $scope.paysValues});
},
function (error) {
$log.error('failure Pays charging', error);
})
};
initPaysData();
I use the factory to get All data from the WS:
BrokoApp.factory('allPaysService', function ($http) {
return {
getPays: function () {
return $http.get('http://localhost:8080/BrokWeb/webresources/referentiel/pays');
}
}
});
this code work but if I add new item to the table is don't shown
the code of add is:
$scope.addPays = function () {
$scope.selectedPy = $scope.libPay;
ngDialog.openConfirm({
template: 'modalDialogAdd',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function () {
console.log('***** before add length=' + $scope.paysValues.length);
ajouterPays();
initPaysData();
console.log('***** after add length=' + $scope.paysValues.length);
$scope.tablePy.total($scope.paysValues.length);
$scope.tablePy.reload();
}, function () {
setNotification(notifications, 'danger', 'Erreur', 'Vous avez annule l operation');
});
};
the console.log show that the length of the List of data is the same before and after Add, the console show:
***** before add length=152
***** after add length=152
XHR finished loading: GET "http://localhost:8080/BrokWeb/webresources/referentiel/pays".
a XHR finished loading: POST "http://localhost:8080/BrokWeb/webresources/referentiel/pays".
the function AjouterPays is
var ajouterPays = function () {
var paysData = {
codAlph2: $scope.codAlph2,
// getting data from the adding form
};
var res = addPaysService.addPys(paysData);
res.success(function () {
setNotification(notifications, 'success', 'Succes', 'Ajout de ' + paysData.libPay);
});
res.error(function () {
setNotification(notifications, 'danger', 'Erreur', 'Erreur est servenue au cours de la creation');
});
// Making the fields empty
$scope.codAlph2 = '';
};
i use the factory addPaysService to post data
BrokoApp.factory('addPaysService', function ($http) {
return {
addPys: function (PyData) {
return $http.post('http://localhost:8080/BrokWeb/webresources/referentiel/pays', PyData);
}
}
});
Can anybody help me.
One simple approach for the updation of the data after you post/save any data or record to the database can be
just have a get request after the save/update is successful
i mean you can call the service/factory function which has the get request to the data base and then assign the response to the scope object of the table
Thank you
In case of the POST success, you can add the created element (if returned by your service) in $scope.paysValues.
Maybe something like that :
var ajouterPays = function () {
var paysData = {
codAlph2: $scope.codAlph2,
// getting data from the adding form
};
var promise = addPaysService.addPys(paysData);
promise.success(function ( response ) {
$scope.paysValues.push( response.data );
setNotification(notifications, 'success', 'Succes', 'Ajout de ' + paysData.libPay);
});
promise.error(function () {
setNotification(notifications, 'danger', 'Erreur', 'Erreur est servenue au cours de la creation');
});
// Making the fields empty
$scope.codAlph2 = '';
};
If your service does not return the created element in case of success, you can simple push the data you sent instead.
PS: note that success() and error() methods on an HttpPromise are deprecated from Angular 1.4.4 (see https://code.angularjs.org/1.4.4/docs/api/ng/service/$http).

Getting $digest erro error when using ng-repeat

I am using ng-repeat to show the User list from SQL Lite Database but when i am binding $scope.Users with result.rows, it gives me the following error
$rootScope:infdig Infinite $digest Loop
<tr ng-repeat="u in Users">
<td>
<button class="w3-btn w3-ripple" ng-click="editUser(u)">✎ Edit</button>
</td>
<td>{{ u.fname }}</td>
<td>{{ u.lname }}</td>
</tr>
controller method:
var showRecords = function () // Function For Retrive data from Database Display records as list
{
db.transaction(function (tx) {
tx.executeSql(selectAllStatement, [], function (tx, result) {
if (result.rows.length > 0) {
dataset = result.rows;
$scope.Users = dataset;
}
});
});
}
Here is Link
Please provide me the solution for this.
I got the solution now.
Returning data from transaction with SQL Lite Database, need to
JSON.stringify
and after that need to parse with
JSON.parse
var showRecords = function () // Function For Retrive data from Database Display records as list
{
db.transaction(function (tx) {
tx.executeSql(selectAllStatement, [], function (tx, result) {
if (result.rows.length > 0) {
$scope.$apply(function () {
$scope.Users = JSON.parse(JSON.stringify(result.rows));
});
}
});
});
}
Here is the working Link

AngularJs Smart Table Pagination - Always Resets to First Page

For some reason, my pagination is always resetting to 1 as the selected page, even though the result comes back from the server with the proper data in the results EG Records 31 - 45) and populate properly in the smart table. What could cause it to always reset the selected page in the pagination view to page 1? Is there a way to say what the selected page is?
Thanks in advance
Controller Method
$scope.getData = function (tableState) {
var pagination = tableState.pagination;
var start = pagination.start || 0;
var number = pagination.number || 10;
$scope.users = UserServicePaging.query({offset: start});
$scope.users.$promise
.then (function (result) { //success
$scope.users = result[0].results;
$scope.rowCollection = $scope.users;
$scope.displayedCollection = [].concat($scope.rowCollection);
tableState.pagination.numberOfPages = Math.ceil(parseInt(result[0].records.total)) / 15;
tableState.pagination.totalItemCount = Math.ceil(parseInt(result[0].records.total));
},
function (error) {//fail
})
.finally(function() {
});
}
Table Header:
<table st-table="displayedCollection" st-safe-src="rowCollection" st-pipe="getData" class="table table-striped">
Table Footer
<td colspan="5" class="text-center">
<div st-pagination="" st-items-by-page="itemsByPage" st-displayed-pages="10"></div>
</td>

Resources