Ember select is not showing the selected item - javascript

I know there is a small problem staring right at my face by can't figure it out.
Consider
{{view Ember.Select
content=baseList
optionLabelPath="content.desc"
optionValuePath="content.id"
selectionBinding="selectedItem"
}}
baseList = [{"id":"item1","desc":"item number is 1"},{"id":"item2","desc":"item number is 2"}]
Below does not work
selectedItem = {"id":"item1","desc":"item number is 1"};
The select drop down does not show any selected item
Below works
selectedItem = baseList.filterBy('id','item1')[0];
Now the select drop down shows the selected item.
What is the problem? I even checked if the order of the properties(id and desc) are proper. Is it because two objects cant be compared directly unless certain algorithm is employed or rather use JSON.stringify?

The problem is that when you specify
selectedItem = {"id":"item1","desc":"item number is 1"};
that hash is a different object from the one in baseList, even though it's lexically identical. So Ember cannot find it in baseList (it's doing a === compare, not a deep compare). When you do the filterBy, on the other hand, it returns the actual object from within baseList, which Ember.Select can then find in baseList.
You might want to try using valueBinding instead; then you can just specify "item1".
BTW, the order of properties makes no difference here or anywhere else in JS.

Related

Can I affect properties of an Angular component based on change of other properties in a non-template-driven fashion?

I'm developing a form with Angular 6 and using some standart components, including ng-select (I'd say that's a requirement). The form is supposed to have rather complicated logic (some field values affect other values or suggestions that ng-select should show). I have a rather general question (hoping that there's an approach which I haven't just found yet), but to stay more specific, let's consider the following example:
I have 2 dictionaries (let's call them categories and items), each item being a "child" of a certain category
I have to let user select a category and an item from each dictionary, for that I have 2 fields like
<ng-select
name="category"
[items]="formSuggestions.categories$ | async"
bindLabel="name"
[(ngModel)]="formFields.category"
></ng-select>
<ng-select
name="item"
[items]="formSuggestions.items$ | async"
bindLabel="name"
[(ngModel)]="formFields.item"
></ng-select>
(in fact, they are wrapped into custom components which I omit for simplicity)
(here formSuggestions.items$ and formSuggestions.categories$ are observables that are filled with suggestions on server response; each item is actually an object having id, name and parentId)
what I need is: when a category is selected, suggestions for items are limited to those which are children of that category; when an item is selected, the category is set automatically
My question is: is there a way in Angular to "subscribe" to changes of one property in model (formFields.item) and apply it to others (formFields.category, formSuggestions.categories$) or the only way to deal with this is to set Outputs like (change) of each field?
The problem with that approach is the actual form is more complicated, for instance:
there's another interface that should be shown in a modal window, where user can choose category (and same for item), so there's multiple points which change the props
item selection should affect another ng-select's suggestions (for another field) and pre-fill some crud interface with default stuff for that item
by the way, I have to show only 10 suggestions each time (suggestion dictionaries are quite long) and there's no "limit" option in ng-select, so I have to affect suggestion list based on field value
...
so I really wonder if I can go less template-driven. Any suggestions, at least for the 2 selections case?
(change) is listening to the classical input change event (not Angular specific). See also MDN-Link
For all [(ngModel)] bound elements, you could also use (ngModelChange) to listen to changes. Thats more Angular style. And it gets even more interesting when you create your own "input" components with the ControlValueAccessor.
The problem in your example is, that you use the subscribed suggestionCategories directly. You could (theoreticly) do a "map" in the observable stream and filter out the unwanted values. But this would only work for each emited event of the observable.
So in your case i fear you have to subscribe to the source, store the result in a component local variable. You also copy the data in a second variable that you use to show the values on the UI.
And whenever the user selects a category, you take the original stored data, filter it and assign the filtered result to your second-variable.
HTML
<ng-select
name="category"
[items]="formSuggestions.categories$ | async"
bindLabel="name"
[(ngModel)]="formFields.category"
(ngModelChange)="filterCategorySugestions($selectedValue)"
></ng-select>
In Typescript you would then use the filterCategorySugestions Method to filter the data and write it into your second variable (mentioned above).
by the way, when filtering, you could afterwards apply a mylist.splice(10) (standard Array method) to limit your results to the first 10. But perhaps you should ensure the order first. :-)
I hope it helps a bit.
warm regards
Jan

Why does AngularJS fail to initialize Select Option (drop list) when ngmodel is used with nested object?

I have a complex object which contains some nested arrays of objects.
Inside one of those inner objects is a value which is the id for an item in another list.
The list is just a look-up of Codes & Descriptions and looks like the following:
[
{ "id": 0, "value": "Basic"},
{ "id": 1, "value": "End of Month (EOM)"},
{ "id": 2, "value": "Fixed Date"},
{ "id": 3, "value": "Mixed"},
{ "id": 4, "value": "Extra"}
]
However, I only carry the value in the nested object.
The Select Option list (drop list) will display all of the values in the previous list so the user can make his/her selection.
Binding Via ng-model
I then bind the value returned from the Select/Option directly to the nested object.
That way, when the user makes a selection my object should be updated so I can just save (post) the entire object back to the server.
Initialization Is The Problem
The selection does work fine and I can see that the values are all updated properly in my nested object when a user selects. However, I couldn't get the UI (select/option) to be initialized to the proper value when I retrieved the (nested) object from the server.
Input Type Text Was Binding Properly
My next step was to add an text box to the form, bind it to the same ng-model and see if it got initialized. It did.
This is a large project I was working on so I created a plnkr.co and broke the problem down. You can see my plnkr in action at: http://plnkr.co/edit/vyySAmr6OhCbzNnXiq4a?p=preview
My plunker looks like this:
Not Initialized
I've recreated the exact object from my project in Sample 1 and as you can see the drop list is not selected properly upon initialization since the value(id) is actually 3, but the drop list doesn't show a selected value.
Keep In Mind: They Are Bound And Selecting One Does Update Values
If you try the plunker you will see that the values are bound to the select/option list because even in the samples which do not initialize properly, when you select an item the other bound items are instantly updated.
Got It Working : Hack!
I worked with it a long time and kept created fake objects to see which ones work and which don't.
It only works, once I changed the value object to one that looks like the following:
$scope.x = {};
$scope.x.y = 3;
Now, I can bind x.y (ng-model="x.y") to select/option and it initializes the select/option list as you would expect. See Sample 2 in the plunker and you will see that "mixed" (id value 3) is chosen as expected.
Additional One Works
I also learned that the following will work:
$scope.lastObj = {};
$scope.lastObj.inner = [];
$scope.lastObj.inner.push(3);
More Nesting
In that case I can bind lastObj.inner to the select/option list and again you can see in Example 3 that it still works. That is an object which contains an array which contains the value.
Minimal Nesting That Fails
However, Sample 4 in the plunker displays the final amount of nesting which does not work with the AngularJS binding.
$scope.thing = {};
$scope.thing.list=[];
$scope.thing.list.push({"item":"3"});
This is an object which contains an array which contains an object with a value. It fails to bind properly on the select/option but not the text box.
Can Anyone Explain That, Or Is It A Bug, Or Both?
Can anyone explain why the select/option fails to bind / initialize properly in this case?
A Final Note
Also, be strong and do not try to explain why you think the nesting of my objects should be different. That's not under discussion here, unless you can tell me that JavaScript itself does not support that behavior.
However, if you can explain that Angular cannot handle this deep of nesting and why, then that is a perfectly valid answer.
Thanks for any input you have.
You are messed up with primitive types. It means you should insert
$scope.vm.currentDocument.fieldSets[0].fields.push({"value":3});
instead of
$scope.vm.currentDocument.fieldSets[0].fields.push({"value":"3"});
Note the difference of {"value":3} and {"value":"3"}
First one defines an object with property "value" with Integer type, and the second one defines an object with property "value" with String type. As Angular checks type match, it becomes that ("3" === 3) evaluates as false, this is why angular cant find selected option.
This is how it supposed to work.
Also note that - as Armen points out - objects are passed by reference as opposed to primitives which are pass-by-value.
Because of this fact, normally initializing a select box via ngModel from JSON (say, from a $resource record) you will need to set the model value to the specific array element/object property that is being internally checked for equality by Angular to the elements in the ngOptions (or repeated options elements with ng-values assigned to the same record objects). No two distinct objects in JS are considered equal, even if they have identical property names/values.
Angular has one way around this: use the "track by" clause in your ngOptions attribute. So long as you have a guaranteed-unique value (such as a record index from a db) Angular will check the value of the property between the model value and the records in ngOptions.
See https://docs.angularjs.org/api/ng/directive/select for more.

Knockout: Propper way of Option-Binding with Model-Instances

By the nature of instances, new anObject({id: 1}) != new anObject({id: 1}).
This leads me to a problem regarding Knockout:
I have an array of possible options (all instances of an model with different property-values) and another model which helds a selection.
From a UI-perspective, I have a simple <select data-bind="options: [...]-binding, which works fine as long as I select an option.
Because my ViewModel can get stored and later recalled in a new applyBinding, I get into the problem of my data-bind not recognizing my selected value and consequentially removing the value.
Now my simplest solution is some sort of initialisation-function, which loops through the options and selects the right model-instance through an id-comparison. After I have the correct instance, I then can apply it to the "selectedValue"-property.
I didn't tried it out yet, but I don't see how it wouldn't work.
Because I don't think that this a strange requirment and a lot of people are using Knockout - I was hoping there was some nicer way of doing this?
Thanks!
Take a look at the Knockout.js documentation for "optionsValue": http://knockoutjs.com/documentation/options-binding.html
Typically you’d only want to use optionsValue as a way of ensuring
that KO can correctly retain selection when you update the set of
available options. For example, if you’re repeatedly getting a list of
“car” objects via Ajax calls and want to ensure that the selected car
is preserved, you might need to set optionsValue to "carId" or
whatever unique identifier each “car” object has, otherwise KO won’t
necessarily know which of the previous “car” objects corresponds to
which of the new ones.

bind complex json object to knockout dropdown menu

I have a complex object being bound to a drop down. See the jsfiddle.
Is this the correct way to bind to a complex object for a drop down menu.
The drop down must bind to an initial value(currently working)
Changing the selected index in the drop down needs to update the knockout object. This is sort of working. The object is updated when save is called so the drop down's object value is being passed to the Format object. -- However.. This value is not updated in the UI.
I am not sure if it is the mapping that needs some work to make format into an observable. The value of SelectedFormat never seems to change from the first load.
any help on getting this to update the ui and text output of the object would be appreciated.
Edited: question to give requirements more clarity
code on js fiddle
1) No its easier than that, just use optionsText point out the member like
optionsText: 'Name'
Object reference is already implicit the optionsValue so you can skip that, if you want to explicit set it anway you can do the same there and just point to the member optionsValue: $data but its not needed. In other words, this would do http://jsfiddle.net/QrvJN/7/
2) The value and options binding are matched on object reference so if initial value and the list of options do not share references you need to match them yourself. You are doing it a little strange though, I did a binding for this that takes care of the problem http://jsfiddle.net/ewSU2/
3) THis is not needed if you check my solution 2)

How can I bind the selected text of a Select box to an object's attribute with Knockout JS, or anything else?

I have a select box pull down that I'm populating with a JSON list returned from a stored procedure, but unfortunately when I update the linked object I need to return the selected text of the pulldown, not the selected index like one would think (poor database design, but I'm stuck with it for now and cannot change it).
Does anyone have any ideas what I can do to keep the selected text synced with the appropriate javascript object's attribute?
You could keep both, the value and the text, if you use subscribers.
For instance, if each of your javascript objects look like this:
var optionObject = {
text:"text1"
value: 1
}
Then your binding would look like:
Where 'OptionsObjects' is a collection of optionObject and selectedOption
has two observable properties: text and value.
Finally you subscribe to the value property of the selectedOption:
viewModel.selectedOption.value.subscribe(function(newValue){
var optionText = viewModel.OptionsObjects[newValue].text;
viewModel.selectedOption.text(optionText);
});
Then if you want to see the new selected option text when the value is changed,
you could have a binding as follows:
<span data-bind:"text:selectedOption.text"></span>
In your particular case you would return selectedOption.text().
So yes, you got what I was getting at. Use the text as the value for the select options rather than using an index. The value really should be something useful, I can't think of any case where I've ever used an index. A number sure, but a number that relates to the application's models in some way (like an id from a database), not to the number of items in the select box.
Well done.

Categories

Resources