Angularjs Default Select Selected Value - angularjs

I generate a table using ng-repeat that loops over user submitted data. Inside of the ng-repeat I have a field, a select, that I use another ng-repeat to build a list of types. This too generates the appropriate select. However, I cannot figure out how to have the select defaulted to the users's value; e.g. User selects book as the type, when the user reloads the page I want the select to have "book" preselected.
<tr ng-repeat="item in userData" ng-include="'templates/bookmarkrow.html'"></tr>
...
<select ng-model="item.type" ng-options="option.name for option in typeOptions track by option.value" class="form-control hidden"></select>
I thought the ng-model would bind the select to the value of item.type. Any ideas?
Additional Details
typeOptions is an array of objects; e.g. [{'name': 'some name', 'value': 'some value', ...}]. As for the data, I'm aware that AngularJS doesn't store the data. Assume in this example that data is coming from a data store; be it database or local storage. The larger point is I will have loaded data in the client side and want to indicate it in the select.

Since angular does not persist data across page reloads the data will be lost when a full reload occurs. If you are using angular routes or ui-router then you can persist data in factories which are singletons.
To save data across page reloads you can (as mentioned) use local storage, cookies or store it the in the backend of your application.
To just initialize a value you can use ng-init

I rewrote my code to use ng-repeat on the option, instead of using ng-options on the select. After that I used ng-selected on the option to decide which option is selected.
<select class="form-control hidden">
<option selected-value="{{option.value}}" ng-selected="{{item.type == option.value}}" ng-repeat="option in typeOptions">{{option.name}}</option>
</select>

Related

Angular ng-model ng-selected

I want to bind a model value to selected item
<select id="hours" ng-model="v.T_Hour">
<option ng-repeat="n in [].constructor(24) track by $index" ng-selected="{{$index==v.T_Hour}}" value="{{$index}}">{{$index>9?$index:"0"+$index}}:00</option>
</select>
I want after the page loads , the value of the model 'v.T_Hour' to be selected in select , i assign the value of the model in the controller, when i view the resulting HTML i see that the value is selected in the HTML code ,but not selected in the select control , and the select control displays an empty item.
Try this
<select
name="name"
id="id"
ng-options="option.name for option in v.data track by option.value"
ng-model="v.selected"
class="form-control inline-forms">
<option value="" selected>{{placeHolder}}</option>
</select>
and in controller
$scope.v = {data:[], selected:{}, placeHolder:""}
$scope.v.data = [{name:"nameOne", value:"valueOne"},{name:"nameTwo", value:"valueTwo"},{name:"nameThree", value:"valueThree"}]
$scope.v.selected = $scope.v.data[0]
$scope.v.placeHolder = "Click to Select"
According Angular documentation ngOption is better way to go than ngRepeat:
Choosing between ngRepeat and ngOptions
In many cases, ngRepeat can be used on elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits:
more flexibility in how the 's model is assigned via the select as part of the comprehension expression
reduced memory consumption by not creating a new scope for each repeated instance
increased render speed by creating the options in a documentFragment instead of individually
Specifically, select with repeated options slows down significantly starting at 2000 options in Chrome and Internet Explorer / Edge.
see: https://docs.angularjs.org/api/ng/directive/select

Cannot display default value in Angular JS Select control when coming from a different service than data in the list

I´ve been looking for other questions about Select using Angular but I think they all talk about populating hardcoded data into the select or maybe just from one service. In my case I want to populate data coming from one service, but choose the default option that has been retrieved from another service.
In this case, every Reservation contains a field with a Customer, so I want to display all customers names in the select (customers.shortName), but the default value comes from the reservation (reservation.customerName). Controller:
$scope.reservation = ReservationFactory.show({id: $routeParams.id});
$scope.customers= CustomersFactory.query();
HTML:
<select ng-model="reservation.customerName" ng-options="x.shortName for x in customers" required class="form-control" id="customerName" placeholder="customer name"><select/>
The data is populated correctly, but I can´t find a way of showing the default data (reservation.customerName). I have also made it work hardcoding the list of customers into the controller or setting for instance the first value of the list as default, but when calling 2 services it doesn´t work. I think it makes sense because I´m calling 2 asynchronous services, so maybe I should do something to refresh the select.
Try this:
<select ng-model="reservation.customerName">
<option ng-repeat="x in customers" value="{{x.shortName}}">{{x.shortName}}</option>
</select>
if the data are asynchronous just wrap in a ng-if the select in order to wait the variables do be populated
<select ng-if="reservation && customers" ng-model="reservation.customerName"
ng-options="x.shortName for x in customers"
required class="form-control" id="customerName" placeholder="customer name">
<select/>

How to pre-select option from <select> tag in Angular with options from a different controller?

I'm using two controllers here. One, productComponentsController, handles a call to our database that pulls back an array of productComponent objects. The other, AddEditArticleController, controls the 'Create New / Edit Existing Article' page.
On my Add/Edit Article page, I want a <select> to populate with productComponents, and, if I am editing an existing Article, to be pre-selected with that Article's current productComponent.
Simple as this seems, I cannot make the field pre-select with the existing productComponent, though it does populate the <select> with them correctly. I've tried ngRepeat and ngOptions and both work for populating the dropdown, but neither works for pre-selecting the existing productComponentID from the array returned by the server.
My HTML, using ngOptions:
<!-- productComponentsController as pvm, AddEditArticleController as vm -->
<select id="componentBox"
ng-model="vm.selectedComponent"
placeholder="Select a Product Component"
ng-change="vm.changeProductID()"
class="form-control input-md"
ng-options="component.name for component in pvm.productComponents track by component.id"></select>
My HTML, using ngRepeat:
<!-- productComponentsController as pvm, AddEditArticleController as vm -->
<select id="componentBox"
ng-model="vm.selectedComponent"
placeholder="Select a Product Component"
ng-change="vm.changeProductID()"
class="form-control input-md">
<option value="{{component.id}}"
ng-repeat="component in pvm.productComponents"
ng-selected="vm.selectOption(component.id)"
ng-bind-html="component.name"></option>
</select>
<!-- vm.selectOption() returns true if the current option's ID equals the productComponentID of the current Article. Therefore this option would be selected. -->
In my AddEditArticleController, I set vm.selectedComponent equal to the productComponentID of the Article that was returned by the database, in the promise.then() of my call. While vm.selectedComponent does change, this doesn't do anything to the dropdown.
Also, in my generated HTML, I get the option: <option value="? number:47 ?"></option> (for an Article where the productComponentID is = 47). Apparently this happens as a result of the model being set to an unknown value but I don't know why the model would be set to anything other than an integer id.
Is this because my select is accessing multiple controllers, or am I missing something obvious here? Any help is greatly appreciated, let me know if more info is needed.
I believe you're looking for ng-init...
<!-- productComponentsController as pvm, AddEditArticleController as vm -->
<select id="componentBox"
class="form-control input-md"
placeholder="Select a Product Component"
ng-change="vm.changeProductID()"
ng-model="vm.selectedComponent"
ng-init="vm.selectedComponent=productComponentID"
ng-options="component as component.name for component in pvm.productComponents track by component.id"></select>
So it turns out that because the model has to be a string, I have to cast the vm.selectedOption to a string whenever it's changed (in this case, in the vm.selectOption function) using String(). This is using ngRepeat. ngInit seems to have no bearing on how my code works.
Boom, that's it, and my code works.

Dynamic Select List Default Selected Item - Angular JS

I have the code listed below which works fine, however when i attempt to add ng-model and related ng-change to the select, an empty option is added. I understanding why, it is because on init the selectedOption for ng-model is empty.
What I want to do is set a default value so when I can use ng-change to set options IsSelected value to true when user selects it. I'm just not sure how to go about this, I have no issues doing this when I'm working with a static generated select list, but for some reason I can't figure it out for this dynamic generated list.
Any input is appreciated!
<div ng-repeat="optionType in productDetailModel.OptionTypes">
<select name="{{optionType.OptionTypeName}}">
<option ng-repeat="option in optionType.Options"
value="{{option.OptionValue}}">{{option.OptionValue}}
</option>
</select>
</div>
Here's plunkr I mocked to give a basic idea of what I have in mind: http://plnkr.co/edit/xBDfc0XzDwsF0mBiFZOv?p=preview
The initial option is blank because the model is initially undefined.
As tymeJV said, initializing your scope inside of your .js will define a default value that will be shown as selected initially.
$scope.modelName = $scope.optionType.Options[0];
It might be helpful to use ng-options instead of ng-repeat. One reason why it might be beneficial is that ng-options does not create a child scope (unlike ng-repeat). This could help simplify linking to your model and avoid confusion.
<select name="{{optionType.OptionTypeName}}" ng-model="modelName" ng-options="option for option in optionType.Options">
</select>
This article covers the basics of ng-options as well as discusses why it would be used as opposed to ng-repeat.
Hope this helps.
Use ng-options when using a select!
<select name="{{optionType.OptionTypeName}}" ng-model="someModel" ng-options="option as option for option in optionType.Options>
</select>
And then set the ngModel to the default option you want selected:
$scope.someModel = $scope.optionType.Options[0]
There is one directive of select element is ng-init but it call once while first time rendering, but if you change the options dynamically then it will not call again. So for that you need to set the model field with value in scope just below of your new option population logic.
$scope.modelName = $scope.Options[0]; // if array
$scope.modelName = $scope.Options[key]; // if Json Object

retrieving values from a server and setting those values as default for a select drop down using angularjs

I am creating an update form to enable my users to modify their data and I want to set a default value in my option element of the data they had stored in the database.Here is the code:
<option value="{{$car[0]->bodyType_id}}" >{{$car[0]->body_type}}</option>
Additionally, I am loading other body types which is fetch from the server using angular http service.
here is the code:
<select name="body_type" class="form-control input-sm" required ng-model = "body" ng-options="bodyType.body_type for bodyType in bodyTypes track by bodyType.id"></select>
I have nested the default option in the select element and the problem is; the default option does not show up and when I use inspect element in chrome I get this:
<option value"?"></option>
why is it not showing and Thanks in advance for helping me fix the problem.

Resources