Getting the Selected Object in Select Option in Angular - arrays

I have this array of objects which I put on the select option and I would want to select one list of object in the select option. However I can't get the value of that list of object. It outputs [object] [Object]. I want to get that selected list of object of the corporation. I assigned it to the [value] and it gets [object][Object].
<div class="select" >
<select class="form-control col-lg-8" #selectedValue (change)="assignCorporationToManage(selectedValue.value)">
<option *ngFor="let corporation of user_corporations" [value]="corporation">{{corporation.corp_name}}</option>
</select>
</div>
ts
assignCorporationToManage(selectedValue) {
console.log(selectedValue)
}

Try like this :
add ngModel for your select and use ngModelChange instead of change.
adding ngModel
using ngModelChange instead of change.
using [ngValue] instead of [value].
component.html
<select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="selectedValue" (ngModelChange)="assignCorporationToManage($event)">
<option *ngFor="let corporation of user_corporations" [ngValue]="corporation">{{corporation.corp_name}}</option>
</select>
Component.ts
assignCorporationToManage(selectedValue) {
console.log(selectedValue)
}

you can get that particular object from the list by using selectedValue.
<select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="selectedValue">
<option *ngFor="let corporation of user_corporations" [ngValue]="corporation">{{corporation.corp_name}}</option>
</select>
in your ts or js file,
const selectedObject = this.user_corporations.find((el: any) => {
return el?.corporation == this.selectedValue;
});
After that, you can use the selectedObject whatever you want.

Related

Default for ng-select not working

I have a form using a select. I'm trying to set a default value, which I want to disable, so the dropdown will show "-- select state --" as the first option and will force the user to make a selection.
My problem is it's not working and the select always starts out blank.
Here is my code:
<select ng-model="contactEditCtrl.addressData.state" style="width: 50%;">
<option ng-disabled="$index === 1" ng-selected="true">--Select State--</option>
<option value="{{state.abbreviation}}" ng-repeat="state in contactEditCtrl.states">{{state.name}}</option>
</select>
Check this one with default <option> and ng-options:
<select ng-model="contactEditCtrl.addressData.state"
ng-options="state.name as state.name for state in contactEditCtrl.states" >
<option value="" ng-disabled="true">-- select state --</option>
</select>
Demo fiddle
It will be converted to:
<select ng-model="addressData.state" style="width: 50%;"
ng-options="state.name as state.name for state in states" class="ng-valid ng-dirty">
<option value="" ng-disabled="true" class="" disabled="disabled">-- select state --</option>
<option value="0">CCCCC</option>
<option value="1">QQQQQQ</option>
</select>
The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.
In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.
Taken from here
So I'd suggest writing it like this.
var app = angular.module('myApp', []);
// Register MyController object to this app
app.controller('MyController', function MyController($scope) {
this.addressData = {state: "--Select State--"};
this.states = [{abbreviation: 'a', name:'ant'}, {abbreviation: 'b', name:'asd'}, {abbreviation: 'b', name:'asd2'}]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='myApp' ng-controller='MyController as contactEditCtrl'>
<select ng-model="contactEditCtrl.addressData.state" style="width: 50%;">
<option value="--Select State--">--Select State--</option>
<option ng-value="state.abbreviation" ng-repeat="state in contactEditCtrl.states">{{state.name}}</option>
</select>
</div>

How to display selected name in <p> from a Select dropdown and send selected id to controller in AngularJS?

I have the following select input in my html which is populated using ng-options. I want to show the selected NAME down below in whereas I want to send the selected ID back to the controller. I get the required id from ng-model="user.category". How can I show the selected name? I also show the names in options.
<select ng-model="user.category" ng-options="category.id as category.name for category in categories" class="form-control" class="select" required>
<option value="{{category.name}}">Select a Category</option>
</select>
<p>Available On : {{user.retailerBranchId}}</p>
<select ng-model="user.category" ng-options="category for category in categories" class="form-control" class="select" required>
<option value="{{category.name}}">Select a Category</option>
</select>
<p>Available On : {{user.category.id}}</p>
If you make retailerBranchId a method you can do it with something like lodash' _.find() (or even native find). You have user.category updating according to your selection, which you say has the id in it, which you can use:
function retailerBranchId() {
return _.get(_.find(this.categories, { id: user.category }), 'name', '');
}
This also fails gracefully; if it can't find any name, or any item that matches the id, it'll return an empty string.
Edit: You would call it in a similar fashion like so:
<p>Available on: {{ user.retailerBranchId() }}</p>
Although really, it's better to use it like this:
<p data-ng-bind="'Available on: ' + user.retailerBranchId()"></p>
Can you try like a below method,
Controller to get selected Category Name:
$scope.getSelectedCategoryDetail=function(selectedCat){
angular.forEach($scope.categories, function(cat){
if(selectedCat===cat.id){
$scope.user.name=cat.name;
}
});
};
Template to have ng-change event:
<select ng-model="user.category" ng-options="category.id as category.name for category in categories" class="form-control" class="select" required>
<option value="{{category.name}}" ng-change="getSelectedCategoryDetail(user.category)">Select a Category</option>
</select>
<p>Category Id : {{user.category}}</p>
<p>Category Name : {{user.name}}</p>

angularjs ng-repeat selected option

How to get the object of selected option in angular js using ng-repeat? Sample fiddle is here where myself populating the dropdown as,
<select ng-model="id" ng-init="id = '-1'" ng-change="select(option)">
<option value="-1">--Select--</option>
<option ng-repeat="option in list" value="{{option.id}}">{{option.name}}</option>
</select>
If someone chose option with id=1, i want to get the object {id:1, name:'A' in $scope variable.
EDIT: Myself tried with ng-options but filtering is not happening as required based on previous dropdown selection. sample fiddle
Use option object in ng-value={{option}} and whenever u select an option your scope.id will have the desired object.
Basically ur ng-model gets populated with selected value.
Just you have to change your option to this
<option ng-repeat="option in list" value="{{'Id : ' + option.id + ' Name : ' + option.name }}">{{option.name}}</option>
Hope this will work for you and you were looking for the same result
You have 2 option to get as Object.
option 1 :
you can use Filter to get Object
<select ng-model="id" ng-init="id = '-1'" ng-change="select((list|filter:{id:id}))">
<option value="-1">--Select--</option>
<option ng-repeat="option in list" value="{{option.id}}">{{option.name}}</option>
</select>
updated fiddler here
option 2 :
set your value as Object (option)
<select ng-model="id" ng-init="id = '-1'" ng-change="select(option)">
<option value="-1">--Select--</option>
<option ng-repeat="option in list" value="{{option}}">{{option.name}}</option>
</select>

returning object from ng-repeat or ng-options?

Ok i have the following:
<select ng-model="item" ng-change="monthpickerclick()">
<option class="animate-repeat" ng-repeat="returnpicker in monthpicker(singles)" value="{{returnpicker.date}}">{{returnpicker.date}}</option>
</select>
each option has an object like so:
returnpicker: Object
$$hashKey: "02O"
Year: 2014
dailyPrice: "165"
date: "January-2014"
minimumStay: 5
month: 0
monthlyPrice: "4000"
reserved: false
weeklyPrice: "880"
how do i get at the object values of each option when selected from my controller?
currently this:
scope.$watch('item', function(){
console.log(scope.item);
});
returns the options string value but i need to get at the month and the year aswell?
how???
I've also tried:
<select ng-model="item" ng-options="o.month as o.month for o in monthpicker(singles)" ng-click="monthpickerclick()">{{item}}</select>
but this strips all the other values from the object from the option.
<select ng-model="item" ng-options="o as o.date for o in monthpicker(singles)">
The ng-model links the selected option to $scope.item using o from ng-options.
In ng-options, the as clause sets the displayed value to o.date.
If monthpicker(singles) returns an array of obects, item will be set the selected object.
Plunkr
How about:
<select ng-model="item" ng-change="monthpickerclick()">
<option class="animate-repeat" ng-repeat="returnpicker in monthpicker(singles)" value="{{returnpicker.date}}">{{returnpicker.date}} {{returnpicker.month}} {{returnpicker.year}}</option>
</select>
Edit:
If your option tag looks like this:
<option ng-click="monthpickerclick()" > ... </option>
Change monthpickerclick() to: monthpickerclick(returnpicker), and feed the object into the function, so its saved to a variable.
<option ng-click="monthpickerclick(returnpicker)" > ... </option>
$scope.monthpickerclick(returnpicker){
$scope.selectedReturnPicker = returnpicker; //save the object
//other stuff
}

Angularjs - Populate select box using ng-options

I have a json object as below
keyword = {
application: ["Athena","EWindow","EWS","FACT","FTP","Hardware","PEN","Hermes","Infrastructure","LNG Tracker","M2M","Maintenance","Microsite","Oracle","Platts.com","PMC","PTO Task","Sametime","Third Party Data","User Error","Vendor","Web Channels","XML-DD","Customer Request","Mark Logic","SBB","Market Engagement Form","Lotus Notes Database","Oracle11i","External News","Stringers","PRP","Kingsman","Hermes-1"],
incidentType: ["Publishing Failure","Brand Damage","Security Failure","Content Creation Failure","Internal failure","External Failure","System Failure","Operational Failure","Editorial Failure","Content inaccuracy","Process Failure","Application Issue","Infrastructure Issue","User Issue","Other","Resend","Data Send validation","Customer issue"],
incidentEnvironment: ["Production","Non-Production","Others"],
incidentPriority: ["Low","Medium","High","Critical"],
incidentLocation: ["Asia Pacific","Europe","New York","New Jersey","Houston","Washington DC","Others"],
incidentStatus: ["Initiation","Work In Progress","Completed","On Hold","Closed","Cancelled"],
incidentCategory: ["ActiveX","Checkin","Checkout","CKEditor","Corrupt Story","Delete Story","Delivering Content","Download-Upload","Filter","Graph-Rich Media","IE Cache","IE Setting","Indicia","InDesign","Infrastructure","Ingest(Table)","Other","PDF","Publish","Search","Table","User Issue"],
incidentTicketTools: ["BMC Remedy"],
}
<div class="col-lg-3">
<select name="txt_inc_Status" class="form-control input-sm" required>
<option selected disabled>
-- Select Status --
</option>
<option ng-repeat="incidentStatus in keywords.incidentStatus" value="{{incidentStatus}}">
{{incidentStatus}}
</option>
</select>
</div>
I need to populate these values in select boxes. Ex: Keywords.application in application select box and so on.
Earlier I used ng-repeat to construct options. But I came to know that it is not advised to do so.
So I am trying to use ng-option but facing difficulties in populating this. Can somebody help me on this?
Also I need to select a default value (random) for these selectbox. How can that be achieved. It didn't work when I used ng-repeat
You can use
<div ng-repeat="(key, value) in keywords">
<select ng-options="item for item in value" ng-init="index = getRandomIndex(value)" ng-model="value[index]">{{item}}</select>
</div>
together with a function to get the random index for current array
$scope.getRandomIndex = function(item){
var index = Math.floor((item.length * Math.random()));
return index;
}
DEMO

Resources