How do I set the default option for select with AngularJS? - javascript

I have been working on trying to set the default pre-selected option for angularJS and for some reason I can't. Here is a link to the relevant Plunkr.
Here is the relevant code:
<select
ng-model="selectedOption"
ng-options="option.value as option.name for option in options">
</select>
I've tried ng-init and a bunch of different ways; I can't figure how to make the top option the preselected one.

The linked answer suggests using ng-init. I would go with assigning default option into selectedOption in controller or directive's link function:
$scope.selectedOption = options[0]
I don't see a need to use another directive for this simple task.

If what you want is to set one of the options pre-defined in options,
in your ng-init do something like this $scope.selectedOption = <value> where <value> is the value property of the object you want to be marked as selected by default. For example 1 if your first object in options would be, {value: 1, name: "Option Number 1}. See code below:
$scope.options = [{value:1, name: "Option 1"}, {value:2, name: "Options 2"}];
$scope.selectedOption = 1;
On the other hand, if you only want to show a predefined option indicating the user to select one option (and not one of the options in your options)...
This is a very simple (but effective way to achieve that). See code below:
<select
ng-model="selectedOption"
ng-options="option.value as option.name for option in options">
<option value="">--Default--</option>
</select>

just update model of the element i.e. selectedOption='yourDefaultValue'
What is the version of angular are you using?
if the latest one, then you can use below code::
<select
ng-model="selectedOption" [ng-value]='yourDefaultValue'`
ng-options="option.value as option.name for option in options">
</select>

Link to updated plunkr : http://plnkr.co/edit/SkS0NqyXpnMcddu80anf?p=preview
Updating model code moved in the function and also select as and track by should be avoided as mentioned in the angular doc
Be careful when using select as and track by in the same expression.

Related

Want to add none as value in select multiple

I am using chosen.jquery.js for select field
<select chosen multiple data-placeholder="Select Body Part(s)"
ng-options="option.Name as option.Name for option in BodyPartList" ng-model="Body_Part">
<option value="" disabled>Select Body Part(s)</option>
</select>
But It shows only data-placeholder value in case of no data in model.
I want to show "Select Body Part(s)" as a option in list.
And user must not select this. Reason is that, I want to add dynamic "Unknown" value in list of Body_Parts. But it not reflect in list.
Same work for select having single selection.
I'm not seeing any problems with your code, as such. Like, I'm trying it and getting the visual behaviour I think you're wanting? Am I missing something?
Html just yours with ng-app etc, javascript is:
var myApp = angular.module('myApp', ['localytics.directives']);
myApp.controller('MyController', function($scope) {
$scope.BodyPartList = [
{ Name: "Arm" },
{ Name: "Leg" }
];
$scope.Body_Part = [];
});
Not sure if data-placeholder is actually doing anything.
Fiddle: http://jsfiddle.net/7187f6d9/
That said, it's not "working". In the fiddle I put a regular select box alongside the chosen one, and the chosen one doesn't seem to be writing to the ng-model correctly. I'm not sure what's up with that.
You can choose the below option
https://harvesthq.github.io/chosen/#optgroup-support
or push another item to the top of the array from server side as your custom label and disable it on client side with the help of ng-if and $index properties of ng-repeat and angularjs. If this make sense then its fine else i can give you a demo.
I hope your query is, you want show a place holder as current selected value but user shouldn't be able to select it.
Instead of making it disabled, make ithidden. Then display an error if a user doesn't select any other options, using the value of placeholder option.
A sample snippet is added below. If value of select is Error, write a case to throw a error back to user.
<select>
<option value="Error" hidden>Select any Company</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
<option value="BMW">BMW</option>
</select>
Hope this helps! If not, ping me with your query. :)

How to set default selected value in Angular Chosen?

I have a select tag to which I am applying angular chosen.
This is my select tag
<select name="rname" id="rname" ng-model="rname" ng-init="rname='CustomReport'"
ng-options="key as value for (key , value) in reportsValuesOptions track by key" chosen>
<option value="">---Select---</option>
</select>
The above select tag is getting populated from below object
$scope.reportsValuesOptions = {'Cash Position Report':'Cash Position Report','Detail Report':'Detail Report','Reconciliation Report':'Reconciliation Report','Summary Report':'Summary Report','Sweep Report':'Sweep Report','FCCS/FBPS Detail Report':'FCCS/FBPS Detail Report','CustomReport':'Custom Report Name'};
The object is a pair of values and options for select tag where the key is options tags value and the value is the option tag text
Now I want to set the default value of the select tag to 'CustomReport' as its option value and 'Custom Report Name' as its option text from the above object, using ng-init.
I tried doing ng-init="rname='CustomReport'", but it doesn't work
How to set its value from object's key value pair?
FULL EXAMPLE
The problem with your solution is since you are giving an object and AngularJS is mostly designed for arrays it causes AngularJS not to be able to track them properly. You probably wanted to write a shorter object for reportsValueOptions but it should be an array of objects which has a form similar to the following:
[
{label: 'First Label', value:'first-option'},
{label: 'Second Label', value:'second-option'}
]
Here is the modified version of your jsfiddle with modified object that also shows which one is selected.
You can also learn more about problems with objects here: https://docs.angularjs.org/api/ng/directive/ngOptions#complex-models-objects-or-collections-
You can simply use ng-init like this
<select ng-init="somethingHere = options[0]"
ng-model="somethingHere"
ng-options="option.name for option in options">
</select>

How to get the selected value of some random dropdown in Javascript/jQuery

<select ng-model="myModel" id="searchAsset" class="search">
<option ng-repeat="asset in assettype" ng-click="assetclick()" value="{{asset}}"></option>
</select>
<select class="search" id="searchLevel">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
While performing some logic on second dropdown, I want to fetch the selected value of the first dropdown or vice-versa. How can I do this?
I tried using $("#searchLevel").value and $("#searchLevel option:selected").text()
The direct answer to this question is to use the .val() method for jQuery like so:
var selectedVal = $("#searchLevel").val();
However, the slightly less direct, but true answer is that you should not be doing anything like this in an angular app - changes in the dom should only be affecting your view model.
When your using angular, jquery is really not required.
As per your code, The first select menu value will be stored in the ng-model attribute value i.e. myModel.
In your second select menu, specific the ng-model as well. You can just fetch the value of the drop down menu by calling ng-model name.
<select class="search" id="searchLevel" ng-model="secondSelect">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
For example,
If you want to access the value inside your controller on change event, then
$scope.changeEventhandlerForFirstSelect = function() {
// $scope.myModel will contain the value
}
Similarly, for second select menu $scope.secondSelect will give that value.
try
$("#searchLevel").val();
with: $("#searchLevel option:selected").text() you get the text not the value.

Pre select an "unknown" option in AngularJS

I'm trying to pre select an option in a select dropdown, I know how to do it if the value for the options are static. But what if they change dynamically? In my case I got a list of albums which updates a lot so I never know what the value of the options will be. I tried selecting the first album in the list by using ng-init like this:
<select class="rounded bold" ng-model="selectedAlbum" ng-init="selectedAlbum='album[0].albumName'">
<option ng-repeat="album in albumsList" value="{{album.albumName}}" ng-bind="album.albumName">
</select>
But with no luck, from my searches I can't really find anything that answers this. It might be ng-options but from what I've seen that doesn't generate options with a binding on them. Like I've done in the code above.
How would I achieve this?
Use the ng-options directive to build you list, and include an option with an empty value:
<select class="rounded bold"
ng-model="selectedAlbum"
ng-options="album.albumName for album in albumsList">
<option value="">-- choose album--</option>
</select>
See this jsBin
In your controller just change the selectedAlbum model to the value you want
$scope.selectedAlbum = albumsList[0].albumName
If albumsList changes, the model (selectedAlbum) may not match any albumName. In this case, selectedAlbum will remain on its previous value, and angular adds an "unknown" option to your select. As I understood your question,in this situation, you want the first item in the new albumList to be selected (which BTW I think is a reasonable action).
In order to achieve this, you can watch albumList and check if selectedAlbum is valid according to new albumList. If not, you can change it to first item:
$scope.$watch("alubmList", function(newAlbumList){
if(angular.isArray(newAlbumList) && newAlbumList.length){
var albumNames = newAlbumList.map(function(album){
return album.name;
});
if(albumNames.indexOf($scope.selectedAlbum)<0)
scope.selectedAlbum = newAlbumList[0].name;
}
});
side note:
you can rewrite your html with ng-options:
<select class="rounded bold" ng-options="album.albumName for album in albumsList"></select>
Simply u can make this with old JavaScript :
var elementid=document.getElementById("elementid");
var unknown_option=elementid.options[1].value;
elementid.value=unknown_option;
//options[1] selects the first option, if 2 then the 2nd.. etc
but of course if u want the last option u will have to make length function then loop or directly "inverted index" :)

Selected value for angular select not be set on page refresh

The selected value of my angularjs select is not being set on page refresh.
It is set if I navigate to a different view and then navigate back again.
The model for the select is saved to local storage and is initialized into the scope onload.
I have checked that the data in the scope is the same in the two situations of navigating away and back again, and refreshing the page. The data is exactly the same.
After a lot of investigation, I see that when the select is pristine, or when the page is refreshed, the select list will have an extra blank option, like first one below with value ?:
<select ng-model="question.answer" class="form-control" ng-options="opt as opt.value for opt in question.options" >
<option value="?" selected="selected"></option>
<option value="0">1</option>
<option value="1">2</option>
</select>
Note The above HTML is the output. My Angular view just has:
<select ng-model="question.answer" class="form-control" ng-options="opt as opt.value for opt in question.options" />
I'm not sure why this would be preventing the correct option from being selected as the correct object is still present at question.answer. See a simplified version of the model below:
var question = {
options: [
{
id: 1,
value: "1"
},
{
id: 2,
value: "2"
}
],
answer: {
id: 2,
value: "2"
}
};
My understanding is that in ng-options, the first opt specifies that this is the value that should be assigned to the variable specified in ng-model. In other words, I will be assigning an object in the options array to question.answer, rather than just the value. I can see by looking at the model that this is the case.
But I'm not sure how Angular will use the value in question.model to determine which option is set as selected.
I wonder if the problem is something to do with the fact that the values of the options are set as indices of question.options and it can't work out from question.answer which index that answer is.
So, I guess my questions are:
- Why is the correct option not being set when this extra <option value="?" selected="selected"></option> is present?
- How does Angular determine how to use the model to set the selected option (aka - what are those funny indices in the option values?)
Sorry this post is so long. Thank for reading.
Update:
Using the Chrome AngularJS Batarang extension, that the value being set to question.answer for a picklist is e.g.:
{
$ref: $["options"][1]
}
which will means the value of the picklist is "2".
So that is how it is using the indices of the options are being used, but is that how I have to set my model? i.e. using the $ref etc?
I edited the answer after I looked at what you were doing.
The ng-options attribute has a track by expression to do just what you're talking about:
ng-options="opt as opt.Value for opt in question.options track by opt.id"
See the updated fiddle: http://jsfiddle.net/CkLEu/6/

Categories

Resources