Angularjs - Populate select box using ng-options - angularjs
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
Related
load `<select>` drop down default value using AngularJS
i need to load default value for my drop downs. first drop down <select class="form-control pz" ng-model="newuser.title"> <option ng-repeat="x in titles" value="{{x}}">{{x}}</option> </select> data for first drop down $scope.titles = ["MR","MRS","MS"]; I need to load "MR" as a default value in my first drop down. second drop down with data. <select class="form-control" ng-model="newuser.assessmentyear" required ng-option="x in assessmentyears"> <option selected>--Select Year--</option> <option ng-repeat="x in assessmentyears" value="{{x}}">{{x}}</option> </select> I need to load "--Select Year--" as a default value. can you help
For the first one, you need to set ng-model value with the value of the first option: $scope.newuser = {}; $scope.newuser.title = "MR"; For the second dropdown add value="" to set default option as selected: <option value="">--Select Year--</option> Note also that this is not needed: ng-option="x in assessmentyears" as you are adding options with ng-repeat. You can see documentation and similar examples here: https://docs.angularjs.org/api/ng/directive/select
Getting the Selected Object in Select Option in Angular
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.
How to set default option for select in angularjs
Now I am trying to set a default value for a select dropdown. but couldn't get it down, code: <div class='paymentmethods subcontent' ng-switch on="editpaymentmethod">{{editselection.selectedmethod=Memethods[paymethodindex]}}// This gives me what I need,but select doesn't. confused? <select ng-model='editselection.selectedmethod' ng-init="editselection.selectedmethod=Memethods[paymethodindex]" id='methods' ng-switch-when='Y'> <option ng-repeat="method in Memethods" value="{{method}}">{{method}}</option> </select> <select ng-model='editselection.selectedmethod' ng-init="editselection.selectedmethod=companies[paymethodindex]" ng-switch-when='N' style='float:left'> <option ng-repeat='companyoption in companies' value="{{companyoption}}">{{companyoption}}</option> </select> </div> JS: $scope.paymethodindex = $scope.Memethods.indexOf(paymethod); console.log($scope.paymethodindex); if(reimbursement=='N') { $scope.paymethodindex = $scope.companies.indexOf(paymethod); } I use paymethodindex to set default value for select dropdown. I can even print out in the page with {{editselection.selectedmethod=Memethods[paymethodindex]}}, I think the index part works fine, any idea?
Use ng-selected to default the selected option, see example in the doc. Alternatively, use ng-options instead of ng-repeat to generate your options.
AngularJS: need to split/parse ng-options value
A legacy database I am working with stores lookup values in a semi-colon separated list (within a single field/column in the table) - which worked fine as a data source for an ASP.NET. But for migrating to AngularJS - I've found no way to intercept the value and split it for separate options in the select element. In the select drop down it simply shows (for example) "1 rep; 2 reps; 3 reps" etc. Can anyone suggest how to split this value so the select options render vertically - each one in it's own option row? This is how the select element looks now: <select ng-model="exerciseVals[$index].reps1" ng-options="value.REPS as value.REPS for (key,value) in lkps ></select>
ng-options works on an array or an object. If I understand your situation correctily, you're getting a large string from the server with semicolon-separated entries. You need to split it into an array. $scope.lkps = stringFromServer.split(";"); Then in HTML: <select ng-model="selectedVal" ng-options="item for item in lkps"> </select>
You can try This , i have included in my code too ! Working Code <div ng-app> <div ng-controller="tempCtrl"> <select> <option ng-repeat="temp in tempdata"> {{temp}} </option> </select> </div> </div> JS CODE var myApp = angular.module('App', ["xeditable"]); myApp.controller('tempCtrl',function ($scope) { alert(); $scope.tempdata = ["1 rep","2 rep","3 rep"]; console.log($scope); });
You can also use angular filter : <select ng-model ='select' ng-options="item for item in 'd;g;f'|split:';'"> <option value="">Nothing selected</option> </select> JS: myApp.filter('split',function(){ return function(str,delimeter) { return str.split(delimeter); } check working example
how to update dropdown value dynamically
I have html code like this <select id="userGroups" name="userGroups" ng-model="userGroups" required class="form-control"> <option value="{{grp.groupId}}" ng-repeat="grp in groups">{{grp.groupName}}</option> </select> and in my controller I want to set the default value but its not working function CreateUserController($scope, grpList) { $scope.groups = grpList.groupList; //it is loading correctly and dropdown is populating correctly $scope.userGroups = "2"; } I am trying to set the userGroups value to 2, but its always showing the first option in select
The best bet here is to use ng-options: <select ng-model="userGroups" ng-options="group.groupId as group.groupName for group in groups"> </select> Fiddle