AngularJS ng-select use an objects property and its value as options - javascript

I'm trying to use this kind of object
{1: 'foo', 2: 'bar'}
with ng-select. I've tried all the four options from the documention it shows for objects but I can't get it to work. I've already searched SO for this kind of question but none of ones I found matches my object.
<select ng-model="selectedCountry" ng-options="value for (key, value) in countries"></select>
When selecting one of the selects that it shows it is using, I guess the object id or index, but not the propety as value. I'm expecting it to get the value 1 when foo is selected and 2 when bar is selected. I'm trying to get the properties as values for the select.
Plunker example.
This is not a typo. it doesn't work in the desired way even after I've removed the ng- prefix of the element. Check the updated Plunker link.

If I'm understanding the question correctly, given {1: 'foo'} you want the dropdown to show foo in the dropdown, and output 1 when selected.
This option would work:
ng-options="key as value for (key, value) in countries. key as sets the output to the key element, value for sets value to the dropdown iterator.

Related

Knockout JS binding element's property to another element

I am trying to bind my selected category's guid property to another ko.observable element. I need to hold that data value in order to send it to the server in a correct JSON format.
Jsfiddle
I am stucked at the binding selected category's guid value to SelectedCategoryGuid in order to appear in JSON file like
'SelectedCategoryGuid': 'guid1'
I have tried $data and $root bindings in the HTML but couldn't achieve it.
Step 1: Remove the quotes around your value data-bind. You should pass a reference to an observable here, not the name of a property.
value: Info.SelectedCategoryGuid
Now, you'll see your guid paragraph print: [object Object]. That's because it's storing the whole category, not just the Guid.
Step 2: To only store the Guid property, use the optionsValue binding. This binding works similar to the optionsText binding you've already used:
optionsValue: 'Guid'
Now things start working as intended. You'll notice the initial bla value gets cleared, because it does not appear in your data set.
Here's the two changes in a fiddle: https://jsfiddle.net/40sh1vjj/

AngularJS - Get Key of Selected Object When ng-options is an Object

I have a <select> with ng-options defined by an object. ng-model captures the selcted object, but I want to also capture the key that was selected. I haven't been able to find a way to do that. Here's an html snippet.
<select class="form-control" id="xaxis" ng-model="model.xaxis" ng-options="k for (k,v) in model.options"></select>
Here's an example of the model.options object:
$scope.model.options = {
"power":{"label":"blah","values":[],"color":"red"},
"voltage":{"label":"blah","values":[],"color":"blue"}
}
If I select "power", my ng-model variable becomes {"label":"blah","values":[],"color":"red"}. I want to also capture, the key "power" as a scope variable. How would one do that?
You can use the key values instead, that way you can easily access data in your controller using $scope.model.options[$scope.model.xaxis].

I can't access the properties of an object even though I can see it's contents

This code used to work just fine when I was using bootstrap's way of dropdown menus.. now that I switched to conventional I dont know why I'm getting this problem. Why can't I access the properties?? Driving me nuts here
HTML
<select class="form-control" ng-model="client" ng-change="clientSelect(client)">
<option value="">--- Please Select ---</option>
<option ng-repeat="client in clientList" value="{{client}}">{{client.clientName}}</option>
</select>
Angular/Javascript
$scope.clientSelect = function (client) {
console.log(client);
console.log(client.clientName); //is undefined
console.log(client.clientId); //is undefined
}
Ouput:
{"clientId":102,"clientName":"Testing"} //i clearly see the properties here...
UsersController.js:130 undefined
UsersController.js:131 undefined
EDIT: when I console.log($scope.clientList) it's fine.. the object of the first item in the array looks like this:
0: Object
$$hashKey: "object:254"
clientId: 102
clientName: "Testing"
_proto: Object
You can't access properties, because the client you get from ng-repeat is a string.
Check the console log of this Plunker I created with your code. You will see that the first consol.log(client) is actually logs out this string: {"clientId":102,"clientName":"Testing 1"}. Therefore, it doesn't have any properties.
From the select docs:
Note that the value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explictly convert it using a directive (see example below) or use ngOptions to specify the set of options. This is because an option element can only be bound to string values at present.
Consider using the ngOptions directive instead of <select> with ng-repeat.

Angular State Dropdown Bound to Country Select

I am trying to have a contextual state dropdown menu that is bound to the country so that only the relevant states display.
I have looked at these two answers for a solution to my implementation.
Angularjs trigger country state dependency
angularjs dependant dropdown option value
But I cannot get them to work and am missing something.
My preferred solution would use some existing ng filter, but I understand that only works on arrays and not objects
<select ng-model="user.state" ng-options="state.name for state in states track by state.id | filter:state.countryid = user.country.id">
I tried converting the object to an array, but that did not seem to work.
I could create a custom filter, but I am hoping to avoid that.
<select ng-model="user.state" ng-options="state.name for state in states track by state.id | customStateFilter:user.country.id">
It seems like there should be some way to get ng-options to work without modifying the data.
Is there an existing Angular filter that works on objects or a way to do conditional logic to filter out the objects dynamically?
You have a few issues here (in addition to a mismatch of state.countryid and country.id):
First, track by comes after the filter (or, in other words, filter comes right after the array, since it filters the array).
Second, you are right - the built-in filter filter only works on arrays, not objects. For objects, you'd need a custom filter.
And lastly, filter filter doesn't accept an expression to evaluate (filter:state.countryid = user.country.id, not to mention that this "expression" that you tried to provide doesn't compare ===, but assigns =). filter accepts as a parameter either a string - to match any property against, an Object specifying which property to match against which value, or a predicate function.
In your case, an object is what you need.
To put this thing together you get:
<select ng-model="selectedState"
ng-options="state.name for state in states | filter: {countryid: user.country.id}:true track by state.id">
<option value="">select state</option>
</select>

select default value using knockout

I have defined my select as below
<select id="selProductType" data-bind="options: productType , value: editProductType , optionsText: 'Name'" />
Below is my code to fill the select in my view model
// Loading combobox with Product Types
$.getJSON("../RestService/Product/AllProductTypes",
function (allData) {
var mappedProductType = $.map(allData, function (item) {
console.log(item.Id + ' ' + item.Name);
return new productType(item);
});
self.productType(mappedProductType);
});
When i initialise page i want to set default value to select. So i tried below
self.editProductType(4);
But it gives me TypeErrror saying object 4 has no method Id.
How to go about it. I have also gone through similar post in stackoverflow but no luck.
Knockout JS binding initial/default value of dropdown (select) list
If you don't specify the :
optionsValue: 'Id'
in data-bind, the binding value in this case must be an object in productType array.
You can select the default object:
self.editProductType(self.productType()[2]);
What is optionsValue?
Similar to optionsText, you can also pass an additional parameter called optionsValue to specify which of the objects’ properties should be used to set the value attribute on the elements that KO generates. You can also specify a JavaScript function to determine this value. This function will receive the selected item as its only argument and should return a string to use for the element’s value attribute.
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.
read more at: http://knockoutjs.com/documentation/options-binding.html

Categories