Bootstrap and select option - angularjs

I'm using angularJS and bootstrap.
javascript:
$http.get('rest/impact').success(function(data) {
$scope.ho.impacts = data;
});
Html :
<select class="form-control" ng-model="ho.impact"
ng-options="imp.id as imp.name for imp in ho.impacts"></select>
And i can retrieve the value like this :
var dataObject = {
impact : $scope.ho.impact,
....
};
The issue is that when i go on the webpage, the select is empty.
Do you know how i can set a default value ?
like the first item of the list ..
Thanks,

You simply need to prepopulate the value referenced by ng-model:
$scope.ho.impact = $scope.ho.impacts[0].id;

You can add a select option with an empty value:
<select class="form-control" ng-model="ho.impact" ng-options="imp.id as imp.name for imp in ho.impacts">
<option value="">Please Select...</option>
</select>
See:
https://docs.angularjs.org/api/ng/directive/select

Related

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.

add default option to angularjs select

I am trying to add a default option to a select with angular but it adds a blank option which strangely disappears when I select it.
I am getting the object to bind to the select using ng-options like this. I am appending a default option like this:
var DocumentSearchController = function (documentsService) {
documentsService.getDocTypes().then(function (results) {
this.documentTypes = results.data;
this.documentTypes.unshift({ DocumentTypeID: null, Name: 'Select a Document Type' });
}.bind(this));
The structure of the objects is:
[{DocumentTypeID: 1, Name: 'Blah'}]
I then use ng-options to bind the objects:
<select class="form-control"
id="documentTypeSelector"
name="documentTypeSelector"
ng-model="vm.selectedDocumentType"
ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID">
</select>
Then annoying this is that a blank option is strangely added that is removed when I select an item.
The options are also not ordered so I suspect my list comprehension is wrong.
To define a default <select> element just assign to ng-model binded variable a default value available in one <option> element (or value).
In your case vm.selectedDocumentType should be set to a vm.documentTypes[theIndexYouChoose].DocumentTypeID
More in general a simplified example could be
// given $scope.options = [1, 2, 3];
<select ng-init="selectedOption=1" ng-option="option for option in options" ng-model='selectedOption'>
</select>
You will find no empty options and the selected option will be 1
You can add an default value this way :
<select class="form-control"
id="documentTypeSelector"
name="documentTypeSelector"
ng-model="vm.selectedDocumentType"
ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID">
<option value="">Select a Document Type</option>
</select>
Edit Or using init function
<select class="form-control"
ng-init="vm.selectedDocumentType= vm.documentTypes[0]"
id="documentTypeSelector"
name="documentTypeSelector"
ng-model="vm.selectedDocumentType"
ng-options="option.Name for option in vm.documentTypes | orderBy:'option.DocumentTypeID':false track by option.DocumentTypeID">
</select>

Angular Select Tags

I am creating a select tag in angular. According to many sites I have read and some posts on here, it says when using the select tag to not use "ng-repeat" on the option tag but use "ng-options" on the select tag so that is how I set it up. My question is, I want a specific option tag selected by default, how do i set the selected attribute using this method?
<select class="form-control" ng-model="selected_group" ng-change="new_group($event)" ng-options="group as (group.group_name | decodeuri) for group in groups"></select>
Choosing a default is easy: set selected_group equal to a particular group in your controller.
The basic idea is that you have a collection and the selected option is to be stored in your ng-model. To designate a selection from the start, you need to put something in ng-model. That would have to be in your controller.
You could add an <option> tag:
<select class="form-control" ng-model="selected_group" ng-change="new_group(selected_group)" ng-options="group as (group.group_name | decodeuri) for group in groups">
<option value="">Please Select an Option</option>
</select>
Here I have created small working demo
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" ng-model="option.group" ng-options="group as (group.name | myfilter) for group in groups">
</select>
</div>
var app = angular.module('myApp', []);
app.filter('myfilter', function() {
return function(v) {
return v == 'test3' ? 'filtered test3' : v;
};
});
app.controller('myCtrl', function($scope) {
$scope.groups = [{id:1,name:'test1', phone:'1234567890'},
{id:2,name:'test2', phone:'1234567890'},
{id:3,name:'test3', phone:'1234567890'}
];
$scope.option={
group: $scope.groups[1]
}
});

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

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