AngularJS can't get selected index of dropdown menu - javascript

I have this dropdown menu:
<select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;">
<option ng-repeat="x in dateTimeSlots"
ng-disabled="x.taken"
ng-value="x.timeSlot">
{{x.dateSlot}}
</option>
</select>
And I am trying to get the selected index on the ng-change. However it always returns -1
$scope.dateTimeChanged = function (selectedItem) {
var index = $scope.dateTimeSlots.indexOf(selectedItem);
console.log(index);
}
Why is it always returning -1....here is a screenshot of my data:
What I am trying to do is get that id value on the selected item. What am I doing wrong?

Well, it is a little uncertain what you really want. Seems to me you are trying to run on two horses :) You bind the ng-model to timeSlot, but what you really want is the index so you easier can grab the object? What about binding the option values direct to the indexes? :
<option ng-repeat="x in dateTimeSlots"
ng-disabled="x.taken"
ng-value="{{ $index }}"> <!-- here -->
{{x.dateSlot}}
</option>
now user.dateTimeSlot will be 0,1,2,3 and so on (when an option is selected). In the change method you now receive the index
$scope.dateTimeChanged = function(selectedItem) {
console.log($scope.dateTimeSlots[selectedItem]) //<-- the selected object by index
}

Related

How to get full drop-down object item using Reactive Forms?

In this case I'm not using ngModel directives.
I want to know how to get the full object binded to the drop down when it change.
Basically, this is what I'm doing:
It's an array of objects with properties, but i don't want only the
value, i want the full object selected
<select #tipoTextoItem (change)="handleChange($item)" name="cmbTipoTexto" class="form-control form-control-sm col-sm-7" id="cmbTipoTexto" formControlName="cmbTipoTexto">
<option *ngFor="let item of textTypes" value="{{item.key}} {{item.value}}
</option>
</select>
Then...
handleChange($event) {
console.log($event.ForExampleGetMyObjectInThisWay());
}
You can use compareWith input property provided by angular. In the function you can compare and return the object. You can use it like:-
<select #tipoTextoItem (change)="handleChange($item)"
[compareWith]="compareFn"
name="cmbTipoTexto"
class="form-control form-control-sm col-sm-7"
id="cmbTipoTexto"
formControlName="cmbTipoTexto">
<option *ngFor="let item of textTypes"
value="{{item}}">{{item.value}}</option>
</select>
In your component.ts file,
compareFn(item1, item2) {
return item1 && item2 ? item1.value === item2.value : item1 === item1;
}
You can look into below link for more info:-
https://angular.io/api/forms/SelectControlValueAccessor#customizing-option-selection
you can use selectedIndex, Here you go :
(change)="handleChange($event.target.selectedIndex)" // change method
handleChange(index) {
console.log(this.textTypes[index]);
}
WORKING DEMO

Using ng-options for a select field inside an ng-repeat how do I filter out previously selected values?

I am creating a select dropdown that can dynamically be added by the user. Clicking a button will execute the following line: "$scope.expenses.push({});" adding a new select dropdown to the page for them to choose from.
This piece is working perfectly fine. But I am running into the issue of the user being able to select the same item in both fields. I have not been able to successfully filter out any other selected values from the dropdown fields. Any pointers would be lovely!
I'm thinking either a custom filter to hide the other selected values or an ng-change function to update the array I am looping over..
Here is my current code:
<div ng-repeat="expense in expenses track by $index">
<label for="itemDescr_{{$index + 1}}">${item_descr}</label>
<select id="itemDescr_{{$index + 1}}" name="itemDescr_{{$index + 1}}" ng-model="expenses[$index].ItemCode" ng-class="{submitted:submitted}" required ng-options="benefit.Code as benefit.Description for benefit in purchDescOptions | removeUsedItemsFilter | orderBy:'Description'">
<option value="">Please select</option>
</select>
</div>
Here is the array ($scope.purchDescOptions) I am looping over:
[
{
Code:"HOU",
Description:"Housewares"
},
{
Code:"ATO",
Description:"Auto Parts, Equipmnt"
},
{
Code:"APP",
Description:"Appliances"
},
{
Code:"CLO",
Description:"Clothing"
}
]

Do dependent dropdown in html using javascript with value and text

I have already a dependent dropdown list in my html form by using only javascript, but when my php script returns values these are just numbered by the position of the text in an array. I would like to have both Value and Text the same value
Here is what I have so far:
SCRIPT IN HEAD TAG:
var my_variable=[
["dropA_opt1","dropA_opt2",dropA_opt3"],
["dropB_opt1","dropB_opt2",dropB_opt3"],
["dropC_opt1","dropC_opt2",dropC_opt3"]
];
function variable(idx) {
var f=document.my_form;
f.drop_nr_2.length=null;
for(var i=0; i<my_variable[idx].length; i++) {
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], i);
}
}
SELECT for main DROPDOWN
<select name="drop_nr_1" onchange="my_variable(this.selectedIndex)">
<option value="" selected disabled></option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
SELECT for dependent DROPDOWN
<select name="drop_nr_2">
</select>
The code i have basically creates the options from the array index, but there is no value="" attribute. From that reason I am getting the array index back - but I need a value="same as the text".
In addition it would be nice to have always the first option in the 2nd dropdown selected and disabled with empty value (like in dropdown 1).
Much appreciate your help
When constructing <option> by using javascript object syntax.
var myOpt = new Option(lbl,val);
The first parameter is the label that user sees it having the second parameter is the value that will be used for this <option> internally.So just modify the constructor line a bit
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
For second requirement add a condition for i===0 when it's true pass additional third parameter (wiz. selected) and make disabled property true
for(var i=0; i<my_variable[idx].length; i++) {
if(i===0){
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i],"selected");
f.drop_nr_2.options[i].disabled= true;
} else{
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
}
}

angular best practice for select show options when other select changes

i'm trying to build a select box that trigger show on options of other select in angular way.
the json that i use build select boxs is
[
{"item_id":1,"item":"rubber","type":"x","facility":"school a"},
{"item_id":2,"item":"pen","type":"x","facility":"school b"},
{"item_id":3,"item":"book","type":"y","facility":"school b"},
]
what i need is 3 select boxes, first one shows all unique type. in above json that would be 'x,y'.
when user select one of them, then it should show all unqiue facility values in other selectbox that has same type as selected.
--if user selected x, then it would show school a and school b
when user select facility, a 3rd selectbox show all uiqiue item as label, and item_id as value where facility = selected facility
<select ng-model="selected.type">
<!-- need to show unique types here -->
</select>
<select ng-model="selected.facility">
<option ng-repeat="s in json" ng-if='selected.type == s.type'>{{s.item}}</option>
</select>
<select ng-model="selected.item">
<option ng-repeat="s in json" ng-if='selected.facility == s.facility'>{{s.item}}</option>
</select>
Current solution
currently what i'm doing is that i wrote a filter
.filter('unique', function() {
return function (arr, field) {
var r = [],final=[];
for(i in arr){
if(r.indexOf(arr[i][field]) == -1){
r.push(arr[i][field]);
final.push(arr[i]);
}
}
return final;
};
})
and doing
<select class="form-control" ng-model="nrequest.facility">
<option ng-repeat="s in facility_services |unique:'facility'" value="{{s.facility}}">{{s.facility}}</option>
</select>
<select class="form-control" ng-model="nrequest.item">
<option ng-repeat="s in facility_services" ng-if='s.facility == nrequest.facility'>{{s.item}}</option>
</select>
it works yet i'm not sure if this is correct way to do it angular way, since i'm still learning this new toy i was hoping for some directions on how to achieve this using ngoptions, or other angularjs best practice

watch the selected value of dropdown with angularjs to populate an array depends on the selected value

I have this fiddle HERE
I want to check for the selected value of the model "sectionSelect", and based on the selected value, weather it's "1" or "2", I want to fill the newArr with the new values that match the selected, in order to filter the min and max prices accordingly.
What I'm doing right now is this ...
if ($scope.sectionSelect == 1) {
for($i=0; $i < arr.length; $i++){
if(arr[$i]['section'] === 1) {
newArr.push(arr[$i]['value']);
}
}
} else if($scope.sectionSelect == 2) {
for($i=0; $i < arr.length; $i++){
if(arr[$i]['section'] === 2) {
newArr.push(arr[$i]['value']);
}
}
}
But that doesn't seem to work.
What should I do?
This is what I have and it's working http://jsfiddle.net/sheko_elanteko/Anj3w/26/
I just want to add the filter functionality to it.
The easiest way to filter things using Angular is to use the built in filtering capabilities. I updated your fiddle here: http://jsfiddle.net/CQyTa/
The changes to the html use the dropdowns to set scope values for what is selected. These values can then be used as filters (in this instance, I'm filtering the min and max values based on the which section is selected).
<select ng-model="sectionSelect" ng-options="section.label for section in sections" ng-change="clearMinMax()">
</select>
<select ng-model="minVal" ng-options="item.value for item in app_data | filter:sectionSelect.section | orderBy:'value'">
<option value="">Min Price</option>
</select>
<select ng-model="maxVal" ng-options="item.value for item in app_data | filter: sectionSelect.section | orderBy:'-value'">
<option value="">Max Price</option>
</select>
Based on what is selected in those dropdowns, you can these use all of those to filter what should show up. The minMax function is in the controller, it just checks whether the value is between the min & max.
<div ng-repeat="item in app_data | filter:sectionSelect.section | filter:minMax | orderBy:'value'">
{{item.value}}
</div>
Let me know if you have any questions!

Categories

Resources