Angular ng-options select not being set to initial value - javascript

I am sending a JSON object in order to initialize some input and select values on my page. The object holds a ShipTo property. and I want the dropdown to be populated with this initial value. For some reason it is not populating, even though they are the same object. I even added in a track by to make sure it is testing equality based on the CompanyName (not exactly sure if thats what track by is meant for) Here is what I have:
the JSON Object:
{
"AccountNumber": "12345",
"Email": null,
"CompanyName": "HK Electric",
"Inactive": false,
"PhoneNumbers": null,
"ChildOfCustomer": "00000000-0000-0000-0000-000000000000",
"Id": "a4aab309-321c-4b09-969c-073eb83b90ad",
"ModifiedBy": null,
"ModifiedOn": "2014-07-16T18:46:52.065Z",
"CreatedBy": null,
"CreatedOn": "2014-07-16T18:46:52.065Z",
"IsDeleted": false
}
vm.shiptos :
[
{
"ShipTo": {
"AccountNumber": "1234",
"Email": null,
"CompanyName": "Mk Mechanical",
"Inactive": false,
"PhoneNumbers": null,
"ChildOfCustomer": "00000000-0000-0000-0000-000000000000",
"Id": "b90f9b8c-3910-43ec-8c14-6294155ce855",
"ModifiedBy": null,
"ModifiedOn": "2014-07-15T23:03:58.47Z",
"CreatedBy": null,
"CreatedOn": "2014-07-15T23:03:58.47Z",
"IsDeleted": false
},
"Addresses": [],
"Customer": null,
"Job": null,
"Orders": []
},
{
"ShipTo": {
"AccountNumber": "12345",
"Email": null,
"CompanyName": "HK Electric",
"Inactive": false,
"PhoneNumbers": null,
"ChildOfCustomer": "00000000-0000-0000-0000-000000000000",
"Id": "a4aab309-321c-4b09-969c-073eb83b90ad",
"ModifiedBy": null,
"ModifiedOn": "2014-07-16T18:46:52.065Z",
"CreatedBy": null,
"CreatedOn": "2014-07-16T18:46:52.065Z",
"IsDeleted": false
},
"Addresses": [],
"Customer": null,
"Job": null,
"Orders": []
}
]
The ngoptions statement in my HTML:
<select id="ddlShipto" name="ddlShipto" data-ng-model="vm.Shipto" data-ng-options="shipto as shipto.ShipTo.CompanyName for shipto in vm.shiptos track by shipto.ShipTo.CompanyName" class="form-control FloatLeft" required>
<option selected="selected" value="">--Select One--</option>
</select>

Not sure track by is not what you're looking for here.
This is the ng-options syntax you are using: select as label for value in array
The part you have wrong is the select parameter. This parameter's expression gets equality checked against the model to determine if it is a match (and will automatically set selected option, etc). So, right now your select parameter is shipto. This means that in order to default to a value, your model needs to be equal to the object in vm.shiptos.
Here's two options:
The first option is to loop through the vm.shiptos and set your model to the one you would like to default. eg:
angular.forEach($scope.vm.shiptos,function(el,i){
//check objects against the JSON object and set the model to the object if desired
if (el.ShipTo.AccountNumber === jsonObject.AccountNumber){
theModelForNgOptions = el;
}
};
The second option you have is to change the ng-options select parameter to something else on the object, so that the model doesn't have to be the whole object. If AccountNumber is your unique identifier to those objects, you could change your options to:
data-ng-options="shipto.ShipTo.AccountNumber as shipto.ShipTo.CompanyName for shipto in vm.shiptos
Now, the select will default only if the attached model is equal to shipto.AccountNumber. Here is an example jsfiddle of this at work: http://jsfiddle.net/ADukg/5392/

Related

How to get User who hosts the event from a Calendly webhook?

I'm receiving an invitee.created webhook from Calendly, which contains Invitee details. I need to get a reference to the Calendly User that hosts the event, so that I can report on it in my application (e.g. keep track of meetings booked with a specific user). How do I do that?
If you need to know which Calendly User (or Users, for collective events) the event was booked with, you need to call Get Event. The event_memberships array will contain a list of User references (URIs). Below is a more detailed step by step guide.
You received a webhook for the event invitee.created. The payload looks something like this:
{
"created_at": "2020-11-23T17:51:19.000000Z",
"created_by": "https://api.calendly.com/users/AAAAAAAAAAAAAAAA",
"event": "invitee.created",
"payload": {
"cancel_url": "https://calendly.com/cancellations/AAAAAAAAAAAAAAAA",
"created_at": "2020-11-23T17:51:18.327602Z",
"email": "test#example.com",
"event": "https://api.calendly.com/scheduled_events/GBGBDCAADAEDCRZ2",
"name": "John Doe",
"new_invitee": null,
"old_invitee": null,
"questions_and_answers": [],
"reschedule_url": "https://calendly.com/reschedulings/AAAAAAAAAAAAAAAA",
"rescheduled": false,
"status": "active",
"text_reminder_number": null,
"timezone": "America/New_York",
"tracking": {
"utm_campaign": null,
"utm_source": null,
"utm_medium": null,
"utm_content": null,
"utm_term": null,
"salesforce_uuid": null
},
"updated_at": "2020-11-23T17:51:18.341657Z",
"uri": "https://api.calendly.com/scheduled_events/GBGBDCAADAEDCRZ2/invitees/AAAAAAAAAAAAAAAA",
"canceled": false
}
}
Here, the payload object is the Invitee. It has an event field that is a reference to the Event that the Invitee booked.
Make a GET call to webhook_data.payload.event - this will be the Get Event operation. The response will look like this:
{
"resource": {
"uri": "https://api.calendly.com/scheduled_events/GBGBDCAADAEDCRZ2",
"name": "15 Minute Meeting",
"status": "active",
"booking_method": "instant",
"start_time": "2019-08-24T14:15:22Z",
"end_time": "2019-08-24T14:15:22Z",
"event_type": "https://api.calendly.com/event_types/GBGBDCAADAEDCRZ2",
"location": {
"type": "physical",
"location": "Calendly Office"
},
"invitees_counter": {
"total": 0,
"active": 0,
"limit": 0
},
"created_at": "2019-01-02T03:04:05.678Z",
"updated_at": "2019-01-02T03:04:05.678Z",
"event_memberships": [
{
"user": "https://api.calendly.com/users/GBGBDCAADAEDCRZ2"
}
],
"event_guests": []
}
}
The event_memberships array in the above payload is an array of Users with whom the event is scheduled (can be more than one, if it's a collective event). You can then do a GET on these User URIs or just compare these URIs with what you've previously saved in the database.

Filter list of Objects according to the month?

I am using graphs, so whenever I choose to show data according to the months, I will have to show data for the each month, I have fields like totalAmount, paidAmount , I should sum data for that month.
const myArray = [
{
"id": 9,
"userId": null,
"invoiceNumber": "biscuitInvoice",
"billedBy": 1,
"billedTo": 2,
"addGst": false,
"invoiceDate": "2021-05-08T12:05:00",
"dueDate": "2021-05-21T12:03:00",
"totalAmount": 11.8,
"discountSymbol": null,
"discountPercent": null,
"subTotal": null,
"notes": null,
"signature": null,
"reachMail": "",
"reachPhoneNo": null,
"businessLogo": null,
"clientName": "Checking Business",
"businessName": "Chocolate Business",
"paymentAmount": 140,
"status": "Created",
"igst": 1.8,
"cgst": 0,
"amount": null,
"sgst": 0,
"businessClient": null,
"businessProfile": null,
"invoiceAttachments": [],
"invoiceItems": [],
"invoiceTerms": []
},
{
"id": 8,
"userId": null,
"invoiceNumber": "invq32",
"billedBy": 1,
"billedTo": 3,
"addGst": false,
"invoiceDate": "2021-04-04T10:10:22",
"dueDate": "2021-05-13T10:10:00",
"totalAmount": 354,
"discountSymbol": null,
"discountPercent": null,
"subTotal": null,
"notes": null,
"signature": null,
"reachMail": "",
"reachPhoneNo": null,
"businessLogo": null,
"clientName": "Checking",
"businessName": "Chocolate Business",
"paymentAmount": 120,
"status": "Paid",
"igst": 54,
"cgst": 0,
"amount": null,
"sgst": 0,
"businessClient": null,
"businessProfile": null,
"invoiceAttachments": [],
"invoiceItems": [],
"invoiceTerms": []
}
]
In that list, I have invoiceDate, one object is of april month and other is of May month.
Click here what I meant to do,I want this functionality
How can I do that, any help?
Here is the function you need:
function getDesiredMonth(data, month) {
return data.filter((item) => item.invoiceDate.split("-")[1] === month)
}
For example, you can call it like this to get May invoices:
getDesiredMonth(myArray, '05')
Let me know if that works for you :)
function filterDataByMonth(data, month){
return data.filter(i => new Date(i.invoiceDate).getMonth() + 1 === month);
}
Answering cause I dont have enough rep to comment.
I guess you can follow these steps:
Initialize aggregate variables that you need (basically sum of sgst or whatever) to 0.
Iterate over list
Use library such as luxon or moment to parse invoice date (they're in ISO, so it'll be straightforward)
Identify month number from parsed object.
Aggregate whatever data you need into the variables initiaziled earlier (eg. total_sgst += current_obj.sgst)
???
Profit?

Can't get values to dropdown from LocalStorage

I have stored values from a html-form to localstorage and when I get the data back from localstorage to form for editing, data will come to input-text fields like it should, but not to dropdown or checkbox fields.
What do I need to do to get values also in dropdowns or checkbox fields? Checkbox has multiple values saved as array so those needs to be separated.
if (localStorage.hasOwnProperty('key')) {
$(function editform() {
var lsdata = JSON.parse(localStorage.getItem('key'));
$('#formid').val(lsdata.FormID);
$('#createdate').val(lsdata.CreateDate);
$('#formfiller').val(lsdata.FormFiller);
$('#customerlist').val(lsdata.CustomerName); //dropdown
$('#contact').val(lsdata.CustomerContact);
$('#worklist').val(lsdata.WorkName); //dropdown
$('#readytodate').val(lsdata.ReadyToDate);
$('#instructions').val(lsdata.Instructions);
$('#amount').val(lsdata.Amount);
$('#amountpcs').val(lsdata.PcsAmount);
$('#chargefull').val(lsdata.ChargeFull);
$('#chargepcs').val(lsdata.ChargeByPcs);
$('#freightcost').val(lsdata.FreightCost);
$('#materiallist').val(lsdata.MaterialName); //checkbox with multiple options
// localstorage value
{
"$id": "1",
"Customer": null,
"Material": null,
"Status": null,
"Work": null,
"FormID": 150,
"CreateDate": "2019-09-17T00:00:00",
"FormFiller": "JOkuMuu",
"CustomerID": null,
"CustomerName": "Wsoy",
"CustomerContact": "Masa",
"WorkID": null,
"WorkName": "Lajitelmapakkaus",
"ReadyToDate": "2019-09-19T00:00:00",
"Instructions": "Tarkasta kirjat ",
"Amount": 50,
"PcsAmount": null,
"ChargeFull": null,
"ChargeByPcs": null,
"FreightCost": null,
"MaterialID": null,
"MaterialName": "Xpohja,Tarra",
"WorkHoursWR": null,
"WorkHoursIT": null,
"WorkHoursCS": null,
"StatusID": null
}
You use hasOwnProperty which is not a method specific to LocalStorage but Object. Instead, you should use setItem/getItem methods of LocalStorage
// localstorage value
var data = {
"$id": "1",
"Customer": null,
"Material": null,
"Status": null,
"Work": null,
"FormID": 150,
"CreateDate": "2019-09-17T00:00:00",
"FormFiller": "JOkuMuu",
"CustomerID": null,
"CustomerName": "Wsoy",
"CustomerContact": "Masa",
"WorkID": null,
"WorkName": "Lajitelmapakkaus",
"ReadyToDate": "2019-09-19T00:00:00",
"Instructions": "Tarkasta kirjat ",
"Amount": 50,
"PcsAmount": null,
"ChargeFull": null,
"ChargeByPcs": null,
"FreightCost": null,
"MaterialID": null,
"MaterialName": "Xpohja,Tarra",
"WorkHoursWR": null,
"WorkHoursIT": null,
"WorkHoursCS": null,
"StatusID": null
}
localStorage.setItem('key', JSON.stringify(data));
if (fetchedData = localStorage.getItem('key')) {
console.log('Item found!', fetchedData);
}else{
console.log('Item NOT found!');
}
Note that, this snippet won't work since same origin error will be thrown.
Hope this helps.

Getting values from JSON multidimensional array?

I have a JSON array that looks like this:
{
"id": 258,
"rawId": null,
"displayName": null,
"name": {
"givenName": "my ame",
"honorificSuffix": "",
"formatted": "my ame",
"middleName": "",
"familyName": "",
"honorificPrefix": ""
},
"nickname": "",
"phoneNumbers": [{
"value": "23423442342424",
"pref": false,
"id": 0,
"type": "mobile"
}],
"emails": null,
"addresses": null,
"ims": null,
"organizations": [{
"pref": "false",
"title": "",
"name": "",
"department": "",
"type": null
}],
"birthday": null,
"note": "",
"photos": null,
"categories": null,
"urls": null
}
I need to get the phoneNumbers >> value from this JSON.
SO I TRIED SOMETHING LIKE THIS:
var d = JSON.parse(test);
alert(test[0].phoneNumbers.value);
The variable test is the JSON shown above.
and I also tried:
alert(d[0].phoneNumbers.value);
and
alert(test.phoneNumbers.value);
But none of the above work.
Is there something that I am missing in my code?
Thanks in advance.
What you showed us is a JSON string (giving a JS object after parsing), not an array.
So d[0].phoneNumbers will not work and d.phoneNumbers will work and will give you an array.
And because it will give you an array, d.phoneNumbers.value will not work, and d.phoneNumbers[0].value will.

have hard time converting json string from server to an array

I get back json from the server, I want to make it an array and just to test it will work I do
JSON.parse(response.data.blocks)
I get this:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at contentblocks.js?KHWUmpg:87149
at <anonymous>
How do I convert blocks to array so I can do this:
let blocks = response.data.blocks.sort(function(a,b){
var x = a.order < b.order? -1:1
return x
})
I got an error that sort did not exist, so I figured I need to make blocks an array so I can sort them.
This is what server sends back
{
"status": "success",
"blocks": {
"0": {
"id": 50,
"content_id": 25,
"type": "title-block-template",
"content": "yeah",
"content_type": null,
"template_block_id": 1,
"user_id": null,
"meta": null,
"created_at": "2017-08-13 17:27:53",
"updated_at": "2017-08-13 17:27:53",
"order": 1,
"settings": [
{
"id": 12,
"key": "order",
"value": "1",
"type": "integer",
"created_at": "2017-08-13 17:17:51",
"updated_at": "2017-08-13 17:17:51",
"pivot": {
"settingable_id": 50,
"setting_id": "12"
}
}
]
},
"1": {
"id": 51,
"content_id": 25,
"type": "images-block-template",
"content": "[]",
"content_type": null,
"template_block_id": 9,
"user_id": null,
"meta": null,
"created_at": "2017-08-13 17:27:53",
"updated_at": "2017-08-13 17:27:53",
"order": 3,
"settings": [
{
"id": 19,
"key": "order",
"value": "3",
"type": "integer",
"created_at": "2017-08-13 17:26:19",
"updated_at": "2017-08-13 17:30:24",
"pivot": {
"settingable_id": 51,
"setting_id": "19"
}
}
]
}
}
}
Sorting the properties of an object
Think of it not as sorting the object, but extracting the properties (into an array) and sorting them by property name.
Let's say your original object (the one you listed out at the bottom of your question) is called server_return_object.
Extract the blocks into an object using
blocks = server_return_object.blocks;
Now we need the keys ("0", "1", etc) of the blocks. Extract them using Object.keys().
block_keys = Object.keys(blocks);
Then we can create an array, with one element for each block. The easiest way is the .map() function, whose takes a list of items and performs a function on them.
block_array = block_keys.map( key => blocks[key] );
You now have in block_array an array of blocks, which you can then sort in any way you like. For example, to sort by the created_at you can use
block_array.sort(function(a,b){return a.created_at > b.created_at } )
Change the function inside the sort(), to return whatever criterion you want to sort on. If it is a simple sort on one of the properties, you can make the criterion, as shown above, a test for greater than (or less than, to sort the other way). More complex orderings are also possible, using multiple criteria.
It may already be parsed!
Two clues.
Already an object
Your display of what the server gives is already an object. It has a property "blocks" that could well be what you are after.
The unexpected token "o"
This is the error you get from JSON.parse when you feed an object into it, instead of a string.
Try this:
x={hello:3};
JSON.parse(x);

Categories

Resources