Add optgroups to angular-selectize asynchronously - angularjs

I am using angular-selectize directive in my project. For this, I need to load optgroups asynchronously. So far I have tried multiple approaches but none of them works. The problem is, you cannot use the data returned by a promise synchronously. On the flip side, I have also been unable to initialize selectize from inside a promise callback. Given below is the code I currently have. Note that it is only to be used to get the idea of the data I'm playing with, not to present it as something you can consider right.
app.js
$http
.get('/get-categories')
.then(getCategoriesSCB, getCategoriesFCB);
function getCategoriesSCB(response) {
if(typeof(response.data) === 'object') {
posControl.menuCategories = response.data[0];
posControl.menuCategoryGroups = response.data[1];
}
else {
getCategoriesFCB(response);
}
}
function getCategoriesFCB(response) {
console.log(response);
}
posControl.menuConfig = {
valueField: 'id',
labelField: 'title',
placeholder: 'Select Category',
optgroupField: 'class',
optgroupLabelField: 'label',
optgroupValueField: 'value',
optgroups: posControl.menuCategoryGroups,
maxItems: 1,
searchField: ['title', 'category'],
onInitialize: function(selectize) {
console.log('selectize is here');
},
}
index.html
<selectize config="POSCtrl.menuConfig" options="POSCtrl.menuCategories" ng-model="POSCtrl.menuModel"></selectize>
data returned by ajax call
[
// this array has to be used for options.
[{
"class": "57b83830babb9",
"category": "Food Menu",
"id": "57b83855b23f9",
"title": "Beverages"
}, {
"class": "57b83830babb9",
"category": "Food Menu",
"id": "57b83855c05de",
"title": "Cuisines"
}, {
"class": "57b83830babb9",
"category": "Food Menu",
"id": "57b83855cdcb4",
"title": "Steaks"
}, {
"class": "57b83830d0899",
"category": "Wholesale Coffee",
"id": "57b83830d0899",
"title": "Wholesale Coffee"
}],
// this array has to be used for optgroups
[{
"value": "57b83830babb9",
"label": "Food Menu"
}, {
"value": "57b83830d0899",
"label": "Wholesale Coffee"
}]
]

You should be able to load a selectize asynchronously by setting the values directly on the posControl.menuConfig:
function getCategoriesSCB(response) {
if (typeof(response.data) === 'object') {
posControl.menuConfig.options = response.data[0];
posControl.menuConfig.optgroups = response.data[1];
}
}

Related

Amchart's Serial Chart page gets freezed when used in Ionic

I am using Amchart's serial chart in ionic framework. I have rendered the serial chart using
var chart = AmCharts.makeChart("chartdiv",
{
"type": "serial",
"categoryField": "Name",
"rotate": true,
"angle": 30,
"depth3D": 40,
"startDuration": 1,
"fontSize": 10,
"theme": "default",
"precision": 4,
"creditsPosition": "bottom-right",
"responsive": {
"enabled": true
},
"categoryAxis": {
"gridPosition": "middle",
"title": "Name",
"inside": true
},
"graphs": [
{
"balloonText": "[[title]] of [[Name]]:[[value]]",
"fillAlphas": 1,
"id": "AmGraph-1",
"title": "X",
"type": "column",
"valueField": "X"
},
{
"balloonText": "[[title]] of [[Name]]:[[value]]",
"fillAlphas": 1,
"id": "AmGraph-2",
"title": "Y",
"type": "column",
"valueField": "Y"
},
{
"balloonText": "[[title]] of [[Name]]:[[value]]",
"fillAlphas": 1,
"id": "AmGraph-3",
"title": "Z",
"type": "column",
"valueField": "Z"
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"title": "Amount"
}
],
"titles": [
{
"id": "Title-1",
"text": "SUMMARY"
}
],
"legend": {
"enabled": true,
"useGraphSettings": true,
"position": "bottom"
},
"dataProvider": $scope.data,
"listeners": [{
"event": "clickGraphItem",
"method": function (event) {
$scope.SelectedX = event.item.category;
$scope.SelectedContext = event.item.dataContext;
$scope.LoadDetailsData($scope.SelectedX, $scope.SelectedContext.Period);
}
}]
}
);
chart.addListener("dataUpdated", zoomChart);
zoomChart();
function zoomChart() {
chart.zoomToIndexes(0, chart.dataProvider.length - (chart.dataProvider.length - 3));
}
I am opening IonicModal on click of graph items and creating another chart. When I close the IonicModal, page which contains the above chart gets freezed untill I press hardware back button.
I am using pie charts few places but not facing this issue on those pages. It seems there is some issue with the serial chart only.
Using IonicModal from template URL option to open Modal -
$ionicModal.fromTemplateUrl('template.html', { scope: $scope })
.then(function (modal) {
$scope.sortModal = modal;
});
$scope.sortShow = function () {
//alert('inside show');
$timeout(function () {
$scope.sortModal.show();
$scope.LoadDetailsChart(); //creating next chart data
}, 0);
};
$scope.sortClose = function () {
$scope.sortModal.hide();
};
$scope.$on('$destroy', function () {
$scope.sortModal.remove();
});
I just need to add paneventenabled property as false here. As per amcharts docs,
This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true.

How to fetch data from json in angularjs Form

How to call the data from json in angularjs form without using backend. i have written this code and here m unable to find a way in last to get data from the json file. someone please help me to move forward from here.
code
$scope.count = $scope.newPreAuth.length;
};
//Delete newPreAuth - Using AngularJS splice to remove the preAuth row from the newPreAuth list
//All the Update newPreAuth to update the locally stored newPreAuth List
//Update the Count
$scope.deletenewPreAuth = function (preAuth) {
$scope.newPreAuth.splice($scope.newPreAuth.indexOf(preAuth), 1);
getLocalStorage.updatenewPreAuth($scope.newPreAuth);
$scope.count = $scope.newPreAuth.length;
};
}]);
//Create the Storage Service Module
//Create getLocalStorage service to access UpdateEmployees and getEmployees method
var storageService = angular.module('storageService', []);
storageService.factory('getLocalStorage', function () {
var newPreAuthList = {};
return {
list: newPreAuthList,
updatenewPreAuth: function (newPreAuthArr) {
if (window.localStorage && newPreAuthArr) {
//Local Storage to add Data
localStorage.setItem("newPreAuth", angular.toJson(newPreAuthArr));
}
newPreAuthList = newPreAuthArr;
},
getnewPreAuth: function () {
//Get data from Local Storage
newPreAuthList = angular.fromJson(localStorage.getItem("newPreAuth"));
return newPreAuthList ? newPreAuthList : [];
}
};
});
Json Code
PreAuth:
======================
URL:http://dev.xxx.com:8080/xxx/preAuth
TYPE:POST
X-Auth-Token t3Z10HGEiYFdzq9lGtr18ycdeAAXmWBEI64rQAJcAte6Ka8Tz96IAhuXHSgpiKufsd
{
"preAuth": {
"claimbId": "newPreAuth",
"claimbStatus": "new",
"patientInfo": {
"patientName": "name",
"gender": "Male",
"dob": 950639400000,
"age": 21,
"contactNumber": 9987654356,
"tpaMemberId": 950639400121,
"policyNumber": "ABC12615627",
"corporateName": "ABC",
"EmployeeId": "XYZ10232",
"otherInsurance": {
"isOtherInsurance": true,
"playerName": "xyx",
"details": "sdfdsafdsfdsf"
},
"familyPhysician": {
"isFamilyPhysician": true,
"physicianName": "fsdf"'c
"physicianContactNumber": 7878748728,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"isFamilyPhysician": false,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"medicalInfo": {
"illnessType": "cancer",
"clinicalFinding": "description",
"ailmentDuration": "2 months",
"ailmentHistory": "description",
"illnessCause": "alcohol",
"provisionalDiagnosis": [
{
"diagnosisName": "abc",
"diagnosisICDCode": "121423"
},
{
"diagnosisName": "xyz",
"diagnosisICDCode": "434543"
}
],
"differentialDiagnosis": [
{
"diagnosisName": "afasdbc",
"diagnosisICDCode": "12431423"
},
{
"diagnosisName": "fdxyz",
"diagnosisICDCode": "434sdf543"
}
],
"clinicalObservations": {
"BP": "120/80",
"CVS": "126",
"P.A.": "abc",
"R.S.": "aa",
"CNS": "dd",
"others": "others"
},
"maternityDetails": {
"maternityType": "G",
"L.M.P.": 950639400000,
"E.D.D.": 950639400000
},
"accidentDetails": {
"accidentCause": "xyz",
"accidentDate": 950639400000,
"isPoliceComplaint": true,
"firNumber": "asfsafds"
},
"pastIllness": [
{
"pastIllnessType": "Diabetes",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Hypertension",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Other",
"isPresent": false,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
}
]
},
"treatmentInfo": {},
"billingInfo": {},
"documents": [
{
"documentId": 12345,
"documentMetadata": {
"documentName": "discharge summary",
"date": 950639400000,
"version": "1.1",
"viewedStatus": false,
"link": "link to view/download document"
}
},
{
"documentId": 12346,
"documentMetadata": {
"documentName": "medical summary",
"date": 950639400000,
"version": "1.0",
"viewedStatus": true,
"link": "link to view/download document"
}
}
]
}
}
I created sample ,it worked this way
// Code goes here
var app = angular.module('app',[]);
app.controller('sample', function($scope,$http){
$scope.name = "advaitha";
$http.get('test.json').then(function(data){
console.log(data.data);
});
})
here is the plunker example
using HTML5 localStorage would require you to serialize and deserialize your objects before using or saving them.
For example:
var myObj = {
firstname: "kisun",
lastname: "rajot",
website: "https://www.kisun.com"
}
//if you wanted to save into localStorage, serialize it
window.localStorage.set("empData", JSON.stringify(myObj));
//unserialize to get object
var myObj = JSON.parse(window.localStorage.get("empData"));
Created a plunker based on your code am able save and retrieve the json data with your code. Please check here

How can I change the attribute in dataset of Fusionchart?

Hi I am implementing a chart in my Angularjs Application, You can see this plunker http://jsfiddle.net/fusioncharts/73xgmacm/ The thing which I want to achieve is to change the value attribute to profit. How can I do this ? I want to display profit not values.
Regards
After 2 days I finally find out the answer. The thing is You cannot change the Fusionchart attribute value but you can change the attribute of your API once you fetched. I used a loop after I fetched the API and replace the 'profit' attribute with value in this way I made the chart. Yes The thing which i had been ignoring was the use of 'variable' instead of scope. If you see this example you would understand Example Here. I am sharing my code May be it helps someone else too.
Give below is my json array which i called tps.json
[
{
"index": "1",
"variantoption": "fan-green",
"company": "sk fans",
"quantity": "650",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "2",
"variantoption": "fan-white",
"company": "al ahmed fans",
"quantity": "450",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "3",
"variantoption": "fan-purple",
"company": "asia fans",
"quantity": "350",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "4",
"variantoption": "fan-yellow",
"company": "falcon fans",
"quantity": "250",
"profit": "78296",
"loss": "8457",
"year": "2016"
}
]
and here is my controller
$http.get('js/tps.json').success(function (data) {
var chartdata = data;
var arrLength = chartdata.length;
console.log(arrLength);
for (var i = 0; i < arrLength; i++) {
if (chartdata[i]['profit'] && chartdata[i]['index']) {
chartdata[i].value = chartdata[i].profit;
delete chartdata[i].profit;
chartdata[i].label = chartdata[i].index;
delete chartdata[i].index;
console.log(chartdata);
}
}
console.log(chartdata);
FusionCharts.ready(function () {
var tps = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"showvalues": "1",
"animation": "1"
},
"data" : chartdata
}
});
tps.render();
});
}
);
}
-Stay foolish stay hungry

how to parse and bind complex JSON in backbone.js with view model controller approach

I am using one complex JSON structure as a result of one Ajax call. Here I need "many different kinds of nested models in one parent model".For each person, I am using one EmployeeContext. I need this as my parent model.
Within this EmployeeContext, I need many different collection having associated model. Example:I have a collection named expenseContextCollection with "expense" as the model of the same.And I have travellContextCollection with travel as the model.
I need to display details of each model and need to update the same and save back to mongo database.
Currently I am using one file for model (EmployeeModel.js),one file for view (EmployeeView.js), one file for template (EmployeePage.html).
And in the EmployeeView.js file I am setting the result of ajax call to model.
initialize: function(instance) {
this.model.set({
"travelContext": ajaxResponse.EmployeeContext.travellContextCollection
});
this.model.set({
"expenseContext": ajaxResponse.EmployeeContext.expenseContextCollection
});
this.render();
}
But I need this travelContext as a backbone collection so that I can loop though it and take each travel model from it
How Can I handle this situation with model view collection approach in backbone.js ?
following is one sample of JSON structure:
{
"EmployeeContext": {
"expenseContextCollection": [{
"currencyType": "INR",
"empID": "00123456",
"imageID": "d69ce74a9b4e075d2111cf0619e27c503d",
"toDate": "11-12-2015",
"billDate": "11-12-2015"
}, {
"currencyType": "INR",
"empID": "00123456",
"imageID": "ab2f78d9f9e7897b4a11c5bc82618d09f4",
"toDate": "25-01-2016",
"billDate": "20-01-2016",
}],
"claimContextCollection": [],
"travellContextCollection": [{
"empID": "00123456",
"isOneWay": true,
"eligibility": "true",
"createTravelRequest": {
"purposeOfTravelDetailsCollection": [{
"isPrimary": "true",
"purposeOfTravel": "Trans",
"leadOpportunity": "BAA12346",
"account": "BASS"
}],
"travelDetailsCollection": [{
"travelToCity": "BANGALORE",
"travelType": "DTR",
"travelTime": "",
"travelFromCity": "CHENNAI",
"checkoutDate": "25-01-2016",
"travelDate": "20-01-2016",
"travelTo": "INDIA",
"travelFrom": "INDIA"
}],
"Preference": {
"empnum": "00123456",
"employeeProfilePreference": {
"emergencyContacCity": "9412345678",
"travelSeatPreference": "aisle",
"smsNotification": "true",
"emergencyContactNumber": "9412345678",
"frequentFlierPreference": {
"frequentFlierNo": "EJK7861",
"frequentFlierAirlines": "Virgin"
},
"employeeContactNumber": "8712345678",
"emergencyContactPerson": "Moll Mathew",
"emergencyContactAddress": "KOOODC",
"travelMealPreference": "vegetarian"
}
},
"otherDetails": {
"smsNotification": true,
"forexAmount": "0",
"forexRequiredDate": "20141002",
"employeeContactNumber": "00123456",
"billable": "true"
},
"emergencyContactDetails": {
"emergencyContacCity": "KOOODC",
"emergencyContactNumber": "9412345678",
"emergencyContactPerson": "Moll Mathew",
"emergencyContactAddress": "KOOODC"
}
},
"billSubmissionMode": "manual",
"travelClass": "Economy",
"access_token": "",
"travelEndDate": "25-01-2016",
"timeStamp": "2015-12-11 16:00:47.395",
"travelType": "DTR",
"travelID": "3000553702",
"travelStartDate": "20-01-2016",
"approvalGIMS": "approvalGIMS",
"expenseCodes": {
"ExpenseTypeCollection": [{
"travelType": "DTR",
"client": "200",
"expenseDescription": "LODGING",
"glAccount": "0000834110",
"lastChangedBy": "",
"expenseCode": "DCN",
"changedOn": "0000-00-00",
"expenseStatus": "ACTIVE"
}, {
"travelType": "DTR",
"client": "200",
"expenseDescription": "BUSINESS",
"glAccount": "0000839301",
"lastChangedBy": "",
"expenseCode": "DMT",
"changedOn": "0000-00-00",
"expenseStatus": "ACTIVE"
}],
"ErrorCodeCollection": [{
"ErrorText": "S",
"ErrorType": "S"
}]
},
"empEmailID": "jaiseephen#gmail.com",
"entry_type": "new_entry",
"approvalBFM": "approverBFM",
"status": "Pending for Expense"
}],
"location_contextCollection": [{
"Status": "success"
}],
"user_context": {
"timeStamp": "2015-12-11 16:00:47.754",
"access_token": "",
"empID": "00123456",
"buDetailsCollection": [{
"buHeadADID": "",
"buHeadName": "",
"buHeadEmail": ""
}],
"empTechManager": {
"techMgrEmpID": "",
"techMgrADID": "",
"techMgrName": "",
"techMgrEmail": ""
},
"empPassportDetails": {
"endDate": "",
"dateOfBirthAsOfPassport": "0000-00-00",
},
"empDetails": {
"secondSupervisorEmpNumber": "00000000",
"empDOB": "15.05.1999",
},
"empEmailID": "jaiseephen#gmail.com",
"supDetailsCollection": [{
"ADID": "FAMM",
"supADID": "FAMM",
"supEmail": "fazee_ammed#gmail.com",
"lastName": "Faz Mammed",
"supCostCenter": "",
"Email": "fazee_ammed#gmail.com",
"CostCenter": "",
"empNumber": "00678444",
"supEmpID": "00678444",
"supName": "Faz Mammed",
"Name": "Faz Mammed"
}],
"altSupDetailsCollection": [{
"supADID": "FAMM",
"supEmail": "fazee_ammed#gmail.com",
"supEmpID": "00678444",
"supName": "Faz Mammed"
}]
}
}
}
I believe the simplest solution would be parse JSON.parse(text). Then, you can use that object in your Backbone model like this:
var obj = JSON.parse(income);
obj.EmployeeContext.travellContextCollection[0]
Also for finding a target value you can create function for searching target node.

Dynamically generated metadata does not display grid

The following data is being used to load and display a grid dynamically. The only difference between the two grids is that the first reader takes in the data below as is, but the second grid only knows about the data and the metaData will be generated on the fly. I placed stubs for the fields and columns as this is not the issue and I haven't decided on how I will generate the data yet.
Both of the readers eventually pass the data below to the JsonReader's readRecords()' function via this.callParent([data]);, but the second one does not display the data. The data is there, but I am not sure why it does not display?
There are two links to demos below. The first is a JSFiddle that loads from memory and the second is a Sencha Fiddle that loads through AJAX.
Snippet
var rawFields = [
{ "name": "year", "type": "int" },
{ "name": "standard", "type": "string" },
{ "name": "bitRate", "type": "float" }
];
var rawColumns = [
{ "text" : "Year", "dataIndex" : "year", "flex" : 1 },
{ "text" : "Standard", "dataIndex" : "standard", "flex" : 1 },
{ "text" : "Bit/Sec", "dataIndex" : "bitRate", "flex" : 1 }
];
Ext.define('Example.reader.DynamicReader', {
extend : 'Ext.data.reader.Json',
alias : 'reader.dynamicReader',
readRecords : function(data) {
var response = {
data: data,
metaData : this.createMetaData(data),
success: true
};
console.log(response);
return this.callParent([response]);
},
createMetaData : function(data) {
return {
idProperty : "id",
fields : rawFields, // These will eventually be generated...
columns : rawColumns // These will eventually be generated...
};
}
});
Data
{
"data": [
{
"id": 0,
"year": 1997,
"standard": "802.11",
"bitRate": 2000000
},
{
"id": 1,
"year": 1999,
"standard": "802.11b",
"bitRate": 11000000
},
{
"id": 2,
"year": 1999,
"standard": "802.11a",
"bitRate": 54000000
},
{
"id": 3,
"year": 2003,
"standard": "802.11g",
"bitRate": 54000000
},
{
"id": 4,
"year": 2007,
"standard": "802.11n",
"bitRate": 600000000
},
{
"id": 5,
"year": 2012,
"standard": "802.11ac",
"bitRate": 1000000000
}
],
"metaData": {
"idProperty": "id",
"fields": [
{
"name": "year",
"type": "int"
},
{
"name": "standard",
"type": "string"
},
{
"name": "bitRate",
"type": "float"
}
],
"columns": [
{
"text": "Year",
"dataIndex": "year",
"flex": 1
},
{
"text": "Standard",
"dataIndex": "standard",
"flex": 1
},
{
"text": "Bit/Sec",
"dataIndex": "bitRate",
"flex": 1
}
],
"success": true
}
}
Demos
The following examples both achieve the same thing, so the only difference is the loading of the data.
Loading from Memory
http://jsfiddle.net/MrPolywhirl/zy4z5z8a/
Loading from AJAX
https://fiddle.sencha.com/#fiddle/d3l
I figured out the answer. I needed to specify a root value for the reader so that the data can be mapped properly.
Ext.onReady(function() {
Ext.widget("dynamicGrid", {
title: 'WiFi LAN Data Rates [Dynamic]',
renderTo: Ext.get('example-grid-dynamic'),
readerType: 'dynamicReader',
// This need to match the 'data' key specified in the `response` object
// that was created in readRecords().
readerRoot: 'data',
data : rawData
});
});
The documentation for root notes that the root property has to map to the data portion of the response.
Documentation for Json.root:
Ext.data.reader.Json.root
root : String
The name of the property which contains the data items corresponding to the Model(s) for which this Reader is configured. For JSON reader it's a property name (or a dot-separated list of property names if the root is nested). For XML reader it's a CSS selector. For Array reader the root is not applicable since the data is assumed to be a single-level array of arrays.

Resources