assign a object to select value - ng-options - javascript

I have a object like this
var myObject = {'123':'something','345':'something else'}
I need to render it as:
<option value={'123':'something'}>something</option>
Here is what i have tried:
ng-options="someObj as label for (id,label) in myObject
Doesn't work!
The model gets the 'label' and not the whole object. Is it even possible to assign a object to value attribute of a SELECT element?
EDIT
Filter for object of the form: {'123':'something','345':'something else'}
.filter('putKeysandValues',function(){
return function(options){
var arr = [];
angular.forEach(options,function(value,key){
arr.push({'key':key,'label':value})
});
return arr;
}
});

You will need to provide an object with key & value attributes to ngOptions. For this you will need to modify the structure of your object to actually have this attributes.
One way is using a filter that returns a valid array for ngOptions:
ng-options="option.label for option in data.availableOptions | putKeyAndValue"
You can check out this plunker with a working filter.
If input is:
[{'123':'something'}, {'345':'something else'}]
Then output is:
[{"123":"something","id":123,"label":"something","$$hashKey":"object:3"},{"345":"something else","id":345,"label":"something else","$$hashKey":"object:4"}]
If you want to remove the obsolete id attribute, then use this filter.
With input the same input, it will return this:
[{"id":123,"label":"something","$$hashKey":"object:3"},{"id":345,"label":"something else","$$hashKey":"object:4"}]
If you still need to return a new array, then do not do it on the filter. In that case you can process the data before passing it to the view, all in the controller like this.
With input:
{'123':'something', '345':'something else'}
Output this:
[{"id":123,"label":"something"},{"id":345,"label":"something else"}]

Using select as something for a (key,value) in set of Values
ng-options="key as value for (key,value) in myObject"
This will put key into the option value and value into label. With that you need to also use ng-model and ngChange. Since you can't pass objects into values, idea is to do that in your controller.
<select ng-model="val" ng-change="changeVal(val)" ng-options="key as value for (key,value) in ops">
In your controller you already have myObject you are gonna add selected item and changeVal function
<script>
var selectedObject;
$scope.changeVal = function(val){
selectedObject = {};
selectedObject[val] = myObject[val];
}
</script>
It's a workaround without putting object into value attr since it is a string.

Related

How to filter array of items with multiple dropdowns on single angularjs custom filter function?

I am facing a problem with the filter function in Angularjs, here I used a common function ng-change for multiple a dropdown. But when I select All(default options) I am getting an empty array of filtered items.
Here is my code
Javascript:
function customFilters() {
vm.filteredItems = $filter('filter')(vm.claimsResData, {
status: vm.status,
member: vm.member,
treatment: vm.treatment
});
}
Html:
<select ng-model="vm.member" class="form-control"
ng-options="names for names in vm.memberNames"
ng-change="vm.customFilters()">
<option value="">All Members</option>
</select>
Any help would be appreciated.
Thanks.
Update your function as below, because when you want to exclude a key from filter you've to pass undefined to its value, but in your code you are passing blank string i.e., ""
function customFilters() {
vm.filteredItems = $filter('filter')(vm.claimsResData, {
status: vm.status,
member: vm.member || undefined,
treatment: vm.treatment
});
}
Only add the selection to the pattern object if the selection is truthy:
function customFilters() {
var patternObj = {}
vm.status && patternObj.status = vm.status;
vm.member && patternObj.member = vm.member;
vm.treatment && patternObj.treatment = vm.treatment;
vm.filteredItems = $filter('filter')(vm.claimsResData, patternObj);
}
A pattern object is used to filter specific properties on objects contained by the array. When that property exists on the pattern object, the objects in the array must have that property.
For more information, see
AngularJS filter Filter API Reference

Change entire object in ng-repeat function AngularJs

Hello I have a questions on ng-repeat on Angularand function for change value.
I have this ng-repeat that cycling a ObjectArray and have a button for reset value.
<div ng-repeat="element in data.elements">
<button ng-click="reset(element)" >reset</button>
</div>
Where data.elements is array of objects example:
[{id:1, name:"element1"},{id:2, name : "element2"}];
In my Controller I set function Reset in $scope that should do a copy of object passed to an default object:
$scope.reset = function(el){
$scope.defaultObject = {id:500, name:"default"};
el = angular.copy($scope.defaultObject);
}
But doesn't work, but if I do:
$scope.reset = function(el){
$scope.defaultObject = {id:500, name:"default"};
el.name = $scope.defaultObject.name;
}
It work.
So I would like that when I do (in this example):
el = angular.copy($scope.defaultObject);
have the object el equals to object $scope.defaultObject my question is, Can i copy entire object without cycling all properties?
You're passing an object to the reset function, then you're overwriting this object. That's it, nothing happens because it won't affect the original object, which is in the data.elements array.
You need to use a different approach. Track the element by its index :
<div ng-repeat="element in data.elements track by index">
<button ng-click="reset(index)" >reset</button>
</div>
...then amend data.elements[index]:
$scope.reset = function(index){
$scope.data.elements[index] = {id:500, name:"default"};
}
are you saying, your updated object does not reflect on the UI? you can try forcing the scope update by running $scope.$apply() after you have assigned the object.

Read html's elements attributes like an array?

I'm thinking for develop a web component form, so... I was wondering my self if it's possible read attributes from a html elements. For example:
<my-component input="3" data-input='"name", "address", "email"' textarea="1" data-textarea='"mensaje"'></my-component>
<script>
while i <= elementattributes.length{
elementattributes[i]
}
</script>
I know that I can access through .getAttribute, but this way will take more code... I just want to be something smart :P
Sorry, my english is poor... I hope you can understand what I want to do :P
:)
If you want to get all of the attributes and their values, you can do something like this:
function getElementAttrs(el) {
var attributes = [].slice.call(el.attributes);
return attributes.map(function(attr) {
return {
name: attr.name,
value: attr.value
}
});
}
var allAttrs = getElementAttrs(document.querySelector('my-component'));
console.log(allAttrs);
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='"mensaje"'></my-component>
The function getElementAttrs returns an array of objects to you with attribute name-value pairs as keys on the object so that you can loop over it, or just pull by key.
You can use dataset to get specific data attribute
var data = document.querySelector('my-component').dataset.input.split(',');
data.forEach(function(e) {
console.log(e)
})
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='"mensaje"'></my-component>
If you want to return all attributes from element you can use attributes which return array-like object, but you can create object with name-value from that
var data = document.querySelector('my-component').attributes, attr = {};
Array.from(data).forEach(function(e) {
attr[e.name] = e.value;
});
console.log(attr['data-input']);
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='mensaje'></my-component>
You can just use .attributes:
document.getElementById("ELEMENT_ID").attributes
This will return an object containing each attribute with its associated value. You can then index the attributes array for specific attributes and use .value for it's corresponding value.

How to bind a value in select box which doesn't present in content using Ember.Select

I have a list of values in content array of Ember.Select. The selected value may or may not be present in the content. But have to show the selected value if doesn't present in content.
For more details check this jsbin
In this if I click on "setColorWithNewValue", it sets the colorObj with new value that doesn't present in colorArray. When I click on "alertValue" button it shows the value in ColorObj but it doesn't selected in select box.
The selected object needs to be in the selection too.
When you call setColorWithNewValue, just push the new object to colorsArray and set the reference to colorObj.
setColorWithNewValue: function() {
var newObject = { 'name': 'White', 'value': '5'};
this.get('colorsArray').push(newObject);
this.set('colorObj', newObject);
}
or without changing the colorsArray
mergedArray: function(){
var arr = new Ember.A(this.get('colorsArray'));
arr.push(this.get('colorObj'));
return arr;
}.property('colorObj', 'colorsArray.#each')
And pass merged array to the select field.
Also look into Ember.Array and Ember.Object. Ember extends native Objects and Arrays.

code to set a select box option value as an object

in an html page i have got, i have a select box like this with values.
<select onChange="return filler(this.value);">
<option value="{'name':'rajiv',age:'40'}">a</option>
<option value="{'name':'mithun',age:'22'}">f</option>
</select>
i want to pass a javascript array or object as the option value.
right now it is treating the option value as a string.
i want it to be an array so that i can access it by
this.value.name,this.value.age in the filler function.
is this possible?
You will not be able to store objects/arrays in the value attribute, however an option would be to use data-* attributes which supports json automatically with jQuery 1.4.3+
<select>
<option data-value='{"name":"rajiv","age":"40"}'>a</option>
<option data-value='{"name":"mithun","age":"22"}'>f</option>
</select>
And using .change()
$("select").change(function(){
alert($(this).find(":selected").data("value").age);
});
Example on jsfiddle
No, not just like that. Values have to be strings. I'd strongly recommend to use something like jQuerys .data() method to hold Arrays or Objects in an expando property.
If it must be in the value, you just need to JSON decode (.parse) it:
var myValue = JSON.parse(this.value);
myValue.age; // 40
myValue.name // rajiv
But again, I don't think this is a good solution. Have a look at http://api.jquery.com/jQuery.data/
Also, jQuery will automatically convert Arrays and Objects if you put the JSON strings in any data- HTML5 attribute. For instance:
<option value="A" data-info="{'name':'rajiv',age:'40'}">something</option>
If you access that node with jQuery now, we automatically got that object in it's data expando
$('option').data('info').name; // === rajiv
You can use parseJSON to convert the string to an object when using it, but the value needs to be a string.
var option = $('select').val();
var selected = $.parseJSON(option);
alert( selected.name + ': ' + selected.age );
React solution
const myObjects = [
{
text: 'a',
value: 1
},
{
text: 'b',
value: 2
},
];
const handleSelectChange = (myStringifyObject) => {
const myObject = JSON.parse(myStringifyObject);
// logic with myObject
}
<input type='select' onChange={(evt) => handleSelectChange(evt.target.value)}>
{myObjects.map((myObject) => (
<option
value={JSON.stringify(myObject)}
key={myObject.value}
>
{myObject.text}
</option>
))}
</input>

Categories

Resources