Hi i need to do this two http get...after that i need to put data in tables and show it...but unfortunately angular doesn't wait the http request. How can i do that? in this code?
Many thanks in advance.
$rootScope.chiamataUno = function() {
var authdata = Base64.encode("DEMVSINT_ADMIN" + ":" + "Password01");
$http.defaults.headers.common["Authorization"] = "Basic " + authdata;
$http.get('http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/P8BPMREST/p8/bpm/v1/queues/DV_ResponsabileBSDL/workbaskets/Responsabile BSDL/queueelements/?cp=DCMSVS_CONN1').success(function(response) {
console.log(response);
$rootScope.rispostaUno = response.queueElements;
$rootScope.risposta = response;
$rootScope.responseJSON = JSON.stringify($scope.risposta);
var newArray = [];
$rootScope.newObjectJSON = [];
$scope.newObject = [];
for(var i=0;i<response.queueElements.length;i++){
var newObject = {
//forse togliere elementi e columns
//elementi:response.queueElements[i],
caseFolderId:response.queueElements[i].caseFolderId.replace("{","").replace("}",""),
caseTaskId:response.queueElements[i].caseTaskId.replace("{","").replace("}",""),
stepName:response.queueElements[i].stepName,
columns:response.queueElements[i].columns,
DV_Caseidentifier_for_eni_OdA: response.queueElements[i].columns.DV_Caseidentifier_for_eni_OdA,
DV_EBELP_ODA: response.queueElements[i].columns.DV_EBELP_ODA,
DV_EINDT_ODA: response.queueElements[i].columns.DV_EINDT_ODA,
DV_MATNR_TXZ01_POS_ODA: response.queueElements[i].columns.DV_MATNR_TXZ01_POS_ODA,
DV_NAMECL_POS_ODA: response.queueElements[i].columns.DV_NAMECL_POS_ODA,
DV_NETPR_WAERS_POS_ODA: response.queueElements[i].columns.DV_NETPR_WAERS_POS_ODA,
DV_PEINH_POS: response.queueElements[i].columns.DV_PEINH_POS,
DV_MENGE_MEINS_POS_ODA: response.queueElements[i].columns.DV_MENGE_MEINS_POS_ODA
};
//console.log("data "+ newObject.DV_EINDT_ODA);
var dataHold = [];
if((newObject.DV_EINDT_ODA !== null) && (newObject.DV_EINDT_ODA !== "?")){
dataHold = newObject.DV_EINDT_ODA;
dataHold = dataHold.split("/");
var dataCorrect = dataHold[2] + "/" + dataHold[1] + "/" + dataHold[0];
//console.log("dataCorrect "+ dataCorrect);
}else{
dataCorrect = newObject.DV_EINDT_ODA;
}
$rootScope.newObjectJSON.push(JSON.stringify(newObject));
//console.log("rootScope.newObjectJSON " + $rootScope.newObjectJSON);
//console.log("dettaglio " + newObject.DV_MENGE_MEINS_POS_ODA + " " + newObject.stepName + " " + newObject.DV_EINDT_ODA);
//console.log("rootScope.caseFolderId " + newObject[i].caseFolderId + " "+ newObject[i].stepName);
newArray.push(newObject);
var queryOdl = "INSERT INTO Tabella_OdL_Temp (caseFolderId, caseTaskId, stepName, DV_Caseidentifier_for_eni_OdA,DV_EBELP_ODA,DV_EINDT_ODA,DV_MATNR_TXZ01_POS_ODA,DV_NAMECL_POS_ODA,DV_NETPR_WAERS_POS_ODA,DV_PEINH_POS,DV_MENGE_MEINS_POS_ODA, Approvata, Rifiutata, Archiviata) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, queryOdl, [newObject.caseFolderId === null ? "null" : newObject.caseFolderId.replace("{","").replace("}",""), newObject.caseTaskId === null ? "null" : newObject.caseTaskId.replace("{","").replace("}",""),newObject.stepName === null ? "null" : newObject.stepName, newObject.DV_Caseidentifier_for_eni_OdA === null ? "null" : newObject.DV_Caseidentifier_for_eni_OdA,newObject.DV_EBELP_ODA === null ? "null" : newObject.DV_EBELP_ODA, dataCorrect === null ? "null" : dataCorrect , newObject.DV_MATNR_TXZ01_POS_ODA === null ? "null" : newObject.DV_MATNR_TXZ01_POS_ODA,newObject.DV_NAMECL_POS_ODA === null ? "null" : newObject.DV_NAMECL_POS_ODA,newObject.DV_NETPR_WAERS_POS_ODA === null ? "null" : newObject.DV_NETPR_WAERS_POS_ODA,newObject.DV_PEINH_POS === null ? "null" : newObject.DV_PEINH_POS,newObject.DV_MENGE_MEINS_POS_ODA === null ? "null" : newObject.DV_MENGE_MEINS_POS_ODA, 0, 0, 0]).then(function(result) {
console.log("insert");
}, function(error) {
console.error(error);
});
}//fine for response.queueElements
//console.log(newObject[2]);
for(var j = 0; j < newArray.length; j++){
if(newArray[j].stepName !== "Item details"){
var casefolderId = newArray[j].caseFolderId.replace("{","").replace("}","");
chiamatadue.push('http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/CASEREST/v1/case/'+ casefolderId +'?TargetObjectStore=CM_DCMSVS_TGT_OBJ');
}
}
$rootScope.chiamataDueNuova();
}) .error(function(response) {
alert("ERROR");
});
}
> Blockquote
var index = 0;
$rootScope.chiamataDueNuova = function(){
if(chiamatadue.length > 0 && index < chiamatadue.length){
var authdata = Base64.encode("DEMVSINT_ADMIN" + ":" + "Password01");
$http.defaults.headers.common["Authorization"] = "Basic " + authdata;
//inserire le autorizzazioni per la chiamata
$http.get(chiamatadue[index]).success(function(result){
index = index + 1;
console.log(result);
$scope.objJ = result.Properties;
var objToInsertOnDB = {
caseFolderId: "",
DV_EBELN_ODA: "",
DV_AEDAT_ODA: "",
DV_EKGRP_EKNAM_ODA: "",
DV_NAME_ODA: "",
DV_NETPR_WAERS_ODA: "",
DV_NAME_CR: "",
DV_StatoPraticaOdA: "",
DV_Caseidentifier_for_eni_OdA: "",
DateCreated: "",
DV_Caseidentifier_for_eni_OdA: ""
};
for(var i = 0; i < $scope.objJ.length; i++){
var actualObj = $scope.objJ[i];
//Ricerco gli elementi da trasmettere nella tabella Chiamata2
if(actualObj['SymbolicName'] === 'DV_EBELN_ODA'){
objToInsertOnDB['DV_EBELN_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_AEDAT_ODA") {
objToInsertOnDB['DV_AEDAT_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_EKGRP_EKNAM_ODA") {
objToInsertOnDB['DV_EKGRP_EKNAM_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NAME_ODA") {
objToInsertOnDB['DV_NAME_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NETPR_WAERS_ODA") {
objToInsertOnDB['DV_NETPR_WAERS_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NAME_CR") {
objToInsertOnDB['DV_NAME_CR'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_StatoPraticaOdA") {
objToInsertOnDB['DV_StatoPraticaOdA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_Caseidentifier_for_eni_OdA") {
objToInsertOnDB['DV_Caseidentifier_for_eni_OdA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DateCreated") {
objToInsertOnDB['DateCreated'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_Caseidentifier_for_eni_OdA") {
objToInsertOnDB['DV_Caseidentifier_for_eni_OdA'] = actualObj['Value'];
}
}
//setto nell'oggetto il caseFolderId
objToInsertOnDB['caseFolderId'] = chiamatadue[index-1].replace("http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/CASEREST/v1/case/","").replace("?TargetObjectStore=CM_DCMSVS_TGT_OBJ","");
console.log("caseFolderId " + objToInsertOnDB.caseFolderId);
console.log("DV_AEDAT_ODA " + objToInsertOnDB['DV_AEDAT_ODA']);
console.log("DV_NAME_CR " + objToInsertOnDB['DV_NAME_CR']);
console.log("DV_StatoPraticaOdA " + objToInsertOnDB['DV_StatoPraticaOdA']);
console.log("DV_EKGRP_EKNAM_ODA " + objToInsertOnDB['DV_EKGRP_EKNAM_ODA']);
var cfId = objToInsertOnDB.caseFolderId;
var queryOdl = "INSERT INTO Tab_OdL2_Temp(caseFolderId, DateCreated, DV_Caseidentifier_for_eni_OdA, DV_EBELN_ODA, DV_AEDAT_ODA, DV_EKGRP_EKNAM_ODA, DV_NAME_ODA, DV_NETPR_WAERS_ODA, DV_NAME_CR, DV_StatoPraticaOdA, Approvata, Rifiutata, Archiviata) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, queryOdl, [objToInsertOnDB.caseFolderId === null ? "null" : objToInsertOnDB.caseFolderId, objToInsertOnDB.DateCreated === null ? "null" : objToInsertOnDB.DateCreated, objToInsertOnDB.DV_Caseidentifier_for_eni_OdA === null ? "null" : objToInsertOnDB.DV_Caseidentifier_for_eni_OdA,objToInsertOnDB.DV_EBELN_ODA === null ? "null" : objToInsertOnDB.DV_EBELN_ODA, objToInsertOnDB.DV_AEDAT_ODA === null ? "null" : objToInsertOnDB.DV_AEDAT_ODA, objToInsertOnDB.DV_EKGRP_EKNAM_ODA === null ? "null" : objToInsertOnDB.DV_EKGRP_EKNAM_ODA, objToInsertOnDB.DV_NAME_ODA === null ? "null" : objToInsertOnDB.DV_NAME_ODA, objToInsertOnDB.DV_NETPR_WAERS_ODA === null ? "null" : objToInsertOnDB.DV_NETPR_WAERS_ODA, objToInsertOnDB.DV_NAME_CR === null ? "null" : objToInsertOnDB.DV_NAME_CR, objToInsertOnDB.DV_StatoPraticaOdA === null ? "null" : objToInsertOnDB.DV_StatoPraticaOdA, 0, 0, 0]).then(function(result) {
console.log("insert Tab_OdL2_Temp");
}, function(error) {
console.error(error);
});
$rootScope.chiamataDueNuova();
});//fine get
}//fine if
$http.get("/your/url").then(function(response) {
// your code that does something with the response HERE
}).catch(function(failedResponse) {
// non-200 response from your HTTP call
})
this is because $http returns a promise. As with all promises, they have a then method which is executed when the promise is resolved or rejected.
If you have more than one request and want to act when all requests are complete you can chain them using $q. See the example below:
$q.all([one.promise, two.promise, three.promise]).then(function() {
console.log("ALL INITIAL PROMISES RESOLVED");
});
var onechain = one.promise.then(success).then(success),
twochain = two.promise.then(success),
threechain = three.promise.then(success).then(success).then(success);
$q.all([onechain, twochain, threechain]).then(function() {
console.log("ALL PROMISES RESOLVED");
});
Related
need help with something.
if (message.content.startsWith(prefix + 'mods')) {
var members = {};
message.guild.members.forEach(member => {
if (member.roles.find(r => r.name === "⭐|Administrator") || member.roles.find(r => r.name === "⭐|Discord Moderator")) {
if (!members[member.hoistRole ? member.hoistRole.name : 'None']) {
members[member.hoistRole ? member.hoistRole.name : 'None'] = [];
}
members[member.hoistRole ? member.hoistRole.name : 'None'].push(member);
}
});
var mods = new Discord.RichEmbed()
.setTitle('Game Administrators')
.setThumbnail(message.guild.iconURL)
.setFooter('Game Administrators', client.user.iconURL)
.setColor(message.guild.me.displayColor)
.setTimestamp();
for (var role in members) {
var str = '';
var arr = members[role];
for (var i = 0; i < arr.length; i++) {
var user = arr[i].user;
if (user.presence.status === 'offline') {
str += '<:offline:496919419298119692> **' + arr[i].displayName + '**\n';
} else if (user.presence.status === 'idle') {
str += '<:idle:496919399257604115> **' + arr[i].displayName + '**\n';
} else if (user.presence.status === 'online') {
str += '<:online:496919410058199042> **' + arr[i].displayName + '**\n';
} else if (user.presence.status === 'dnd') {
str += '<:dnd:496919391376506880> **' + arr[i].displayName + '**\n';
}
}
arr = members[role];
mods.addField(role, str);
}
message.channel.send({ embed: mods });
}
We have the first role Admin and the second Moderator, but the command is showing the moderator first and then Admin. What is the best way to do, that appear in role order?
You can use the .sort() function.
Example:
// V12
message.channel.send(message.guild.roles.cache.map(role => role.name).sort().join(", "))
// V11
message.channel.send(message.guild.roles.map(role => role.name).sort().join(", "))
I'm trying to create a service that return me the NgTableParams so I don't need to do it every time I need a table.
I was able to do it and it worked, but only if i have only one table using it in my controller, if I try to use it in a second table look's like the service mess the parameters of the fist and second table and stop working.
I tried to change the service to a factory and tried to make a angular.copy of the service so each copy create one different table yet noting worked.
Every time i need a table it is like this:
$scope.tableParams = NgTableDataService.getGenericTableParams($scope.onboardcomputerstatus, $scope.filterObject);
$scope.searchTable = { filter: '' };
$scope.tableParams = new NgTableParams({
count: $scope.session.user.tablePagination,
filter: $scope.searchTable.filter
}, {
counts: rowsPerPageTemplate,
getData: function (params) {
var funcFilter = function (item) {
var pfilter = params.filter().filter.toUpperCase();
return item.onboardComputer.id.toString().indexOf(pfilter) >= 0
|| (!!item.onboardComputer.remainingMonitoringMsgs ? item.onboardComputer.remainingMonitoringMsgs : "").toString().indexOf(pfilter) >= 0
|| $filter('date')((!!item.onboardComputer.oldestMonitoringTimestamp ? item.onboardComputer.oldestMonitoringTimestamp : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| $filter('date')((!!item.lastCommunicatio ? item.lastCommunicatio : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| $filter('date')((!!item.lastRegister ? item.lastRegister : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| item.vehicle.code.toUpperCase().indexOf(pfilter) >= 0
|| item.vehicle.name.toUpperCase().indexOf(pfilter) >= 0;
}
filteredData = params.filter() ? $filter('filter')($scope.onboardcomputerstatus, funcFilter) : $scope.onboardcomputerstatus;
if (!!filteredData && filteredData.length >= 0) {
params.total(filteredData.length);
var rowsPerPageTemplateWithAllData = rowsPerPageTemplate.slice();
var isFound = rowsPerPageTemplateWithAllData.some(function (element) {
return element === filteredData.length;
});
var filteredDataLength = filteredData.length + (isFound ? 1 : 0);
rowsPerPageTemplateWithAllData.push(filteredDataLength);
params.settings().counts = rowsPerPageTemplateWithAllData;
if (params.count() === MY_CONSTANTS.TABLE_PAGINATION_ALL) {
params.count(filteredDataLength);
}
if (params.total() <= params.count()) {
params.page(1);
}
var x = $filter('orderBy')(filteredData, params.orderBy());
var y = x.slice((params.page() - 1) * params.count(), params.page() * params.count());
return y;
} else {
return null;
}
}
});
So I tried to do a factory like this:
angular.module('control-room').factory('NgTableDataFactory', function (
$filter, MY_CONSTANTS, NgTableParams, Session
) {
var ngTableObj = {};
ngTableObj.tableData = {};
ngTableObj.filterObject = {};
ngTableObj.session = Session.get();
ngTableObj.defaultDateFormat = (!!ngTableObj.session.company ? ngTableObj.session.company.dateHourFormatHTML : null);
ngTableObj.tablePagination = (!!ngTableObj.session.user ? ngTableObj.session.user.tablePagination : MY_CONSTANTS.QTD_REG_TAB_INDEX);
ngTableObj.NgTableParamsFactory = new NgTableParams({
count: ngTableObj.tablePagination,
filter: ""
}, {
counts: rowsPerPageTemplate,
getData: function (params) {
if (!!params.filter().filter && params.filter().filter != '') {
var pfilter = params.filter().filter.toUpperCase();
} else {
var pfilter = '';
}
let filteredData = params.filter() ? $filter('filter')(ngTableObj.tableData, ngTableObj.funcFilterFactory(ngTableObj.filterObject, pfilter)) : ngTableObj.tableData;
if (!!filteredData && filteredData.length >= 0) {
params.total(filteredData.length);
var rowsPerPageTemplateWithAllData = rowsPerPageTemplate.slice();
var isFound = rowsPerPageTemplateWithAllData.some(function (element) {
return element === filteredData.length;
});
var filteredDataLength = filteredData.length + (isFound ? 1 : 0);
rowsPerPageTemplateWithAllData.push(filteredDataLength);
params.settings().counts = rowsPerPageTemplateWithAllData;
if (params.count() === MY_CONSTANTS.TABLE_PAGINATION_ALL && filteredDataLength > 0) {
params.count(filteredDataLength);
}
var x = $filter('orderBy')(filteredData, params.orderBy());
var y = x.slice((params.page() - 1) * params.count(), params.page() * params.count());
return y;
} else {
return null;
}
}
});
ngTableObj.findPropertyValue = function (obj, propertyList){
let aux = obj;
for(property of propertyList){
aux = aux[property];
}
return aux
};
ngTableObj.funcFilterFactory = function (f_Object, p_filter) {
return function (item) {
var result = false;
if (!!f_Object.columnNames) {
f_Object.columnNames.forEach(function (row) {
if (!result){
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = (propertyValue ? propertyValue.toString() : "").toUpperCase().indexOf(p_filter) >= 0 || result;
}
});
};
if (!!f_Object.translateNames) {
f_Object.translateNames.forEach(function (row) {
if (!result){
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = $filter('translate')((propertyValue != null ? propertyValue.toString() : "").toUpperCase()).indexOf(p_filter) >= 0 || result;
}
});
}
if (!!f_Object.dateFormat) {
f_Object.dateFormat.forEach(function (row) {
if (typeof(row) == 'string') {
if (!result) {
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = propertyValue ? $filter('date')(propertyValue, ngTableObj.defaultDateFormat).toUpperCase().indexOf(p_filter) >= 0 : false || result;
}
}else {
if (!result) {
const propertyValue = ngTableObj.findPropertyValue(item, row[0].split('.'));
result = propertyValue ? $filter('date')(propertyValue, row[1]).toUpperCase().indexOf(p_filter) >= 0 : false || result;
}
}
});
}
return result;
};
};
return ngTableObj
});
and in the controller is like this:
$scope.filterObject = {
columnNames : ['onboardComputer.id', 'onboardComputer.remainingMonitoringMsgs', 'vehicle.code', 'vehicle.name' ],
dateFormat : ['onboardComputer.oldestMonitoringTimestamp', 'lastCommunicatio', 'lastRegister' ]
};
$scope.tableFactory = NgTableDataFactory;
$scope.tableFactory.tableData = $scope.onboardcomputerstatus;
$scope.tableFactory.filterObject = $scope.filterObject;
$scope.tableFactory.session = Session.get();
$scope.tableParams = $scope.tableFactory.NgTableParamsFactory
Like I said, this way it work well, but only if i use one time, if I have 2 tables it stop working
The goal is to return a boolean value defining if a Job can be posted based on Earned staffing.
There are different pieces that come from three different sql tables. Rather than making a sql query that returns all of them in one result, i'm trying to understand how to use the $q.all function. The problem is that I am not getting a promise back from the service. The error is: TypeError: Cannot read property 'then' of undefined
There a few articles on this subject but most that I have found are old and still refer to using defer. I have tried the suggestions in the others and none of them have worked. They mentioned that the $q.all needs a return, and to return the $q.resolve and $q.reject for the return values.
Here is the code in my service:
function isMDOLevelAllowed(mdoLevel, finance) {
this.crData = "";
this.pData = "";
var mdoLevelToMatch = "", mdoMatrix = "", mdoOnRollsTotal = 0, mdoAuthTotal = 0;
var mdoVarianceTotal = 0, mdoPending = 0, mdoPendingThisLevel = 0;
return $q.all([
getCRO36ByFinance(finance),
epEarnedMDOSDOResource(finance),
getPendingByFinance(finance)
]).then(function (data) {
var crData = data[0];
var eData = data[1];
var pData = data[2];
var mdoData = crData.filter(function (m) { return m.jobType === "MDO"; });
mdoLevelToMatch = mdoData.filter(function (m) { return m.payGrade === mdoLevel; })[0];
mdoVarianceTotal = mdoData.reduce(function (a, b) { return a + b.variance; }, 0);
mdoMatrix = mdoData.map(function (m) { return { payGrade: m.payGrade, authorized: m.totalAuthorized }; });
mdoPending = pData.mdoTotalCount;
mdoPendingThisLevel = eval("pData.mdO" + mdoLevelToMatch.payGrade + "Count");
// Check if over Total Authorized
if (mdoVarianceTotal + mdoPending < 0) {
// Check if over Paylevel Authorized
if (mdoLevelToMatch.variance + mdoPendingThisLevel < 0) {
return $q.resolve();
}
else {
return $q.reject();
}
}
else {
return $q.reject();
}
}).$promise;
}
var service = {
getEarnedByFinance: getEarnedByFinance,
getCRO36ByFinance: getCRO36ByFinance,
getPendingByFinance: getPendingByFinance,
isMDOLevelAllowed: isMDOLevelAllowed,
isSDOAllowed: isSDOAllowed
};
return service;
How about trying:
function isMDOLevelAllowed(mdoLevel, finance) {
var defer = $q.defer();
this.crData = "";
this.pData = "";
var mdoLevelToMatch = "", mdoMatrix = "", mdoOnRollsTotal = 0, mdoAuthTotal = 0;
var mdoVarianceTotal = 0, mdoPending = 0, mdoPendingThisLevel = 0;
$q.all([
getCRO36ByFinance(finance),
epEarnedMDOSDOResource(finance),
getPendingByFinance(finance)
]).then(function (data) {
var crData = data[0];
var eData = data[1];
var pData = data[2];
var mdoData = crData.filter(function (m) { return m.jobType === "MDO"; });
mdoLevelToMatch = mdoData.filter(function (m) { return m.payGrade === mdoLevel; })[0];
mdoVarianceTotal = mdoData.reduce(function (a, b) { return a + b.variance; }, 0);
mdoMatrix = mdoData.map(function (m) { return { payGrade: m.payGrade, authorized: m.totalAuthorized }; });
mdoPending = pData.mdoTotalCount;
mdoPendingThisLevel = eval("pData.mdO" + mdoLevelToMatch.payGrade + "Count");
// Check if over Total Authorized
if (mdoVarianceTotal + mdoPending < 0) {
// Check if over Paylevel Authorized
if (mdoLevelToMatch.variance + mdoPendingThisLevel < 0) {
defer.resolve();
}
else {
defer.reject();
}
}
else {
defer.reject();
}
});
return defer.promise;
}
Take a note on how i defined var defer = $q.defer(); and then returned defer.promise just once. You dont need to return resolve and reject
Thank you for your help. I got it to work. I changed the $q.resolve, $q.reject to a return true or false, and removed the $promise at the end.
function isMDOLevelAllowed(mdoLevel, finance) {
this.crData = "";
this.pData = "";
var mdoLevelToMatch = "", mdoMatrix = "", mdoOnRollsTotal = 0, mdoAuthTotal = 0;
var mdoVarianceTotal = 0, mdoPending = 0, mdoPendingThisLevel = 0;
return $q.all([
getCRO36ByFinance(finance),
epEarnedMDOSDOResource(finance),
getPendingByFinance(finance)
]).then(function (data) {
var crData = data[0];
var eData = data[1];
var pData = data[2];
var mdoData = crData.filter(function (m) { return m.jobType === "MDO"; });
mdoLevelToMatch = mdoData.filter(function (m) { return m.payGrade === mdoLevel; })[0];
//mdoOnRollsTotal = mdoData.reduce(function (a, b) { return a + b.totalOnRolls; }, 0);
//mdoAuthTotal = mdoData.reduce(function (a, b) { return a + b.totalAuthorized; }, 0);
mdoVarianceTotal = mdoData.reduce(function (a, b) { return a + b.variance; }, 0);
mdoMatrix = mdoData.map(function (m) { return { payGrade: m.payGrade, authorized: m.totalAuthorized }; });
mdoPending = pData.mdoTotalCount;
mdoPendingThisLevel = eval("pData.mdO" + mdoLevelToMatch.payGrade + "Count");
// Check if over Total Authorized
if (mdoVarianceTotal + mdoPending < 0) {
// Check if over Paylevel Authorized
if (mdoLevelToMatch.variance + mdoPendingThisLevel < 0) {
return true;
}
else {
return false;
}
}
else {
return false;
}
});
}
I would like to know if it was possible to update several pages in a single controller?
I need to refresh my home page after adding data to my list.
For now I use a pull to refresh in my homepage, but I would like it to update after an addition in my list.
my controller :
.controller('addCRCtrl', function ($scope, $state, $stateParams, $ionicPopup, $ionicLoading, $timeout, AppService) {
let loadData = () => {
$ionicLoading.show();
$scope.loading=true;
$scope.form = {};
$scope.formProjet = {};
$scope.form.patient = idjeune;
$scope.form.dateVisite = new Date();
AppService.patient(idjeune).then(function (response) {
$scope.patient = response;
console.log(response);
});
AppService.user().then(function (response) {
$scope.bene1 = response;
console.log(response);
});
AppService.hopitaux().then(function (response) {
$scope.hopitaux = response;
});
AppService.lieuxlist().then(function (response) {
$scope.lieux = response;
});
AppService.userByAntenneAddCR().then(function (response) {
console.log(response);
$scope.listeBene = JSON.parse(JSON.stringify(response));
});
AppService.typeVisite().then(function (response) {
$scope.listeVisite = JSON.parse(JSON.stringify(response));
});
AppService.projet(idjeune).then(function (response) {
$scope.projets = response;
});
AppService.getCategorie().then(function (response) {
$scope.categorieprojet = response;
console.log(response);
if (update) {
$scope.updating = update;
$scope.form.dateVisite = new Date(cr.date);
for (let i in $scope.lieux) {
if ($scope.lieux[i].id == cr.idLieu) {
$scope.lieu = $scope.lieux[i];
break;
}
}
$scope.form.lieudetail = cr.lieudetail;
$scope.bene1 = {
id: cr.bene1,
nom: cr.benevole1
}
$scope.bene2 = {
id: cr.bene2,
nom: cr.benevole2
}
$scope.bene3 = {
id: cr.bene3,
nom: cr.benevole3
}
console.log("Benevole 1 : ", $scope.bene1);
console.log("Benevole 2 : ", $scope.bene2);
console.log("Benevole 3 : ", $scope.bene3);
$scope.form.description = cr.compteRenduVisite;
$scope.form.todo = cr.todo;
$scope.form.etatpatient = cr.etatPatient;
for (let i in $scope.listeVisite) {
if ($scope.listeVisite[i].id == cr.typeVisite) {
$scope.typeVisite = $scope.listeVisite[i];
break;
}
}
for (let i in $scope.projets) {
if ($scope.projets[i].id == cr.idProjet) {
$scope.projet = $scope.projets[i];
break;
}
}
$timeout(() => { $ionicLoading.hide(); $scope.loading=false;;}, 6000);
}
else
$timeout(() => { $ionicLoading.hide(); $scope.loading=false;}, 2000);
});
}
$scope.$on('$ionicView.beforeEnter', function (event, viewData) {
loadData();
});
$scope.addCr = function () {
$ionicLoading.show();
let isValid = $scope.form.dateVisite && $scope.patient && $scope.bene1 && $scope.form.description && $scope.form.todo;
isValid = isValid && $scope.form.etatpatient && $scope.typeVisite;
let formInvalid = () => {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
template: '<p style="text-align: center;">Veuillez renseigner tous les champs</p>'
});
}
if (!isValid) {
formInvalid();
return;
}
$scope.form.lieu = ($scope.lieu)? $scope.lieu.id:0;
$scope.form.bene1 = $scope.bene1.id;
$scope.form.bene2 = ($scope.bene2) ? $scope.bene2.id : null;
$scope.form.bene3 = ($scope.bene3) ? $scope.bene3.id : null;
$scope.form.lieudetail = ($scope.form.lieudetail) ? $scope.form.lieudetail : "-";
let temp = $scope.form.dateVisite;
//$scope.form.dateVisite = $scope.form.dateVisite.toISOString().slice(0, 10);
let newProject = false;
$scope.form.typeVisite = $scope.typeVisite.id;
switch ($scope.typeVisite.id) {
case 3:
newProject = true;
isValid = isValid && $scope.cprojet && $scope.formProjet.description && $scope.formProjet.titre;
break;
case 4:
case 5:
if ($scope.projet) $scope.form.projet = $scope.projet.id;
isValid = isValid && $scope.projet;
break;
default:
$scope.form.projet = 0;
break;
}
for (var i in $scope.hopitaux) {
if ($scope.hopitaux[i].nom === $scope.patient.hopital) {
$scope.form.hopital = $scope.hopitaux[i].id;
}
}
for (var j in $scope.form) {
if ($scope.form[j] == null) {
if (j == 'bene2' || j == 'bene3')
$scope.form[j] = 0;
else
delete $scope.form[j];
}
}
if (!isValid) {
formInvalid();
return;
}
let callService = () => {
var myform = angular.copy($scope.form);
if (update)
myform.dateVisite = new Date($scope.form.dateVisite.getTime() + 86400000).toISOString().slice(0, 10);
else
myform.dateVisite = $scope.form.dateVisite.toISOString().slice(0, 10);
console.log(myform);
let idtogo = (update) ? cr.id : null;
AppService.addCR(myform, idtogo).then(function (response) {
update = false;
cr = null;
var alertPopup = $ionicPopup.alert({
title: 'Ajout Réussie !',
template: '<p style="text-align: center;">Merci d\'avoir renseigné les informations relatives à la visite !</p>'
});
$scope.form.dateVisite = temp;
console.log(response);
$ionicLoading.hide();
$state.reload('menu.ficheJeune');
$state.go('menu.ficheJeune');
});
}
if (!newProject || update)
callService();
else {
$scope.formProjet.categorie = $scope.cprojet.id;
$scope.formProjet.patient = idjeune;
var myprojectform = angular.copy($scope.formProjet);
console.log(myprojectform);
AppService.addProject(myprojectform).then((response) => {
console.log(response);
if (response) {
AppService.projet(idjeune).then(function (response) {
for (let i in response) {
console.log("Response :", response);
let temp = false;
for (let j in $scope.projets) {
if (response[i].id == $scope.projets[j].id) {
temp = true;
}
}
if (!temp) {
$scope.form.projet = response[i].id;
callService();
break;
}
}
});
}
});
}
};
AppService.refreshToken().then(function (response) {
if ($scope.token) {
console.info('Refresh');
}
});
})
For now, to update my first page I do:
$state.reload('menu.ficheJeune');
$state.go('menu.ficheJeune');
But I would also like to update a second page called 'menu.home'.
I thank you in advance
You can use this in your homeCtrl :
$scope.$on('$ionicView.beforeEnter', function() {
console.log('beforeEnter');
// your code
});
exports.getFbFriendsFromFbIdAndFbAccessTokenTest=function(id,token){
var request = require('request');
var urls = "https://graph.facebook.com/" + id + "/friends?access_token=" + token;
request(urls, function(error, response, body) {
if (!error && response.statusCode == 200) {
var output = JSON.parse(body);
output.sort(function(a,b){
if (a.name > b.name)
return 1;
if (a.name < b.name)
return -1;
// a must be equal to b
return 0;
});
console.log(output);
}
});
}
I want to sort the facebook friend's list in ascending order. Currently i am getting the following result in console:
`{ data: `
[ { name: 'xxx', id: '547dsad1' },
{ name: 'xxx', id: '55324iii' },
{ name: 'xxx', id: '55yyy' },
........
........
But it gives error that object output has no property sort.
I have also used Array.prototype:
Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
}
output.sortByProp('name');
But then it shows the same error that object output has not property sortByProp.
Is there any other way to solve this problem?
output is an object, output.data is an array
Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
};
console.log(output.data.sortByProp('name'));