AngularJS set dropdown option to be selected depending what value as saved - angularjs

I have list of records where in each record contains dropdown.
For each record I want the select box value to be selected on page load depending upon what value as saved. Currently in example I have created two arrays, one containing various price list and other array object containing all saved data. I want the price to be kept selected for each record in select box depending upon what price is saved in second array currently.

You can use ng-init as follows:
<select ng-init="Price=Item.Price" ng-model="Price" ng-options="option.Price as option.Price for option in Prices">
But, remove the track by to accomplish this.
As you asked in comments:
<select ng-model="Price">
<option ng-repeat="option in Prices" ng-selected="{{ option.a == Price }}" value="{{ option.price }}">
{{ option.price }}
</option>
</select>
In controller:
$scope.Price = 100;

Related

ng-options Set ng-model value as selected item in blank list

I have a different case here with ng-options
I have two modes for my app. New mode and Edit mode
I have SELECT input types for DISTRICTS and VILLAGES. The VILLAGES select is populated based on DISTRICT selection using ng-change event of DISTRICT select. This works fine in NEW mode.
But when in EDIT mode, the DISTRICT is correctly showing the value of ng-model. But the VILLAGE select input item is not showing the ng-model value. This is because, the village select does not have any items populated in it as the ng-change event of DISTRICT never triggers in EDIT mode.
I still want to show the ng-model value of VILLAGE as selected item in the drop down, even if it does not have any options in it. (in EDIT mode)
Any ideas of how this can be done? Please shed some light
Here the code below for DISTRICT select
<select class="form-control" name="district" id="field_district" ng-model="vm.apeksha.district" required
ng-change="vm.updateblocks(vm.apeksha.district)"
ng-options="x.malDistName as x.malDistName for x in vm.masterDistricts " >
Here is the code for VILLAGE select input item
<select class="form-control" name="village" id="field_village" ng-model="vm.apeksha.village"
ng-options="village.M as village.M for village in vm.villagelist track by village.M"
required >
<option value="{{ vm.apeksha.village }}">{{ vm.apeksha.village }}</option>
</select>
The option item is not shown even if there is value on "vm.apeksha.village"
In controller, we have a function which uses a factory to update the list of data corresponding to each DISTRICTS. Here is he code of controller
/**
* Update dropdown boxes of VILLAGES, THALUKS, PO AND BLOCS
* based on district selection
*/
vm.updateblocks = function(districtName) {
vm.blockslist = masterDataPopulator.getBlocksForDistrict(districtName);
vm.postofficelist = masterDataPopulator.getPostOfficesForDistrict(districtName);
vm.villagelist = masterDataPopulator.getVillagesForDistrict(districtName);
vm.thalukList = masterDataPopulator.getTaluksForDistrict(districtName);
};
Any ways to do this?
I suggest you to go for ng-options in this case instead of ng-repeat with <option> tag.
The above is the list of category. Selecting one category will load the dropdown with the subcategories as below,
Category
<select class="home_search_select" name="d1" ng-model="selectedd1" ng-change="homeChanged()" ng-options="cat as cat.category_name for cat in categorydata track by cat.category_id" id="d1">
<option ng-value="">Select Category</option>
</select>
SubCategory
<select class="home_search_select" name="d2" id="d2" ng-model="selectedd2" ng-options="subcat.ID as subcat.Name for subcat in selectedd1.Subcategory track by subcat.ID">
<option class="home_search_select" value="">Select Sub Category</option>
</select>
When the first one is selected, bind the value to the ng-model of second dropdown in the ng-change event
$scope.homeChanged=function(){
console.log($scope.selectedd1)
}
$scope.selectedd2 ={
"Name": "Two Wheeler",
"ID": "1"
};
LIVE DEMO

Angular 1.5 and setting a selected option for a dynamic generated select?

I have nested data objects that I want to show to a user based on the filters they have selected. I am a bit new to angular but finding how to solve this problem has taken me a while now and not really got anything good.
<tr ng-repeat="stockItem in stock | filter : stockFilter ">
<td>{{stockItem.dateCreated | date:'dd/MM/yyyy (HH:mm)'}}</td>
<td>{{stockItem.sku}}</td>
<td>
<select class="form-control">
<option ng-repeat="supplierOrderStock in stockItem.supplierStock | filter : supplierSelectionFilter"
value="{{supplierOrderStock.supplierId}}" >
£{{supplierOrderStock.price}}
</option>
</select>
</td>
</tr>
I have check boxes on the top of the page and when you check or uncheck them the drop downs get updated with the filtered data.
Problem is that the SELECTED drop down is random, usually the first one that was selected on initial render.
I just want the cheapest value to be shown in the drop downs and the way the data is sorted that is always going to be the first select option.
How do I set the drop down selected value, for each nested repeat to be either the cheapest one or just simply the always the first drop down??
You can try to use the NgOption directive instead:
<div class="col col-50">
<span>Orientation</span> <br>
<select name="orientation" id="orientation" ng-options="option.label for option in data.filters.basics.orientations track by option.id" ng-model="data.selectedOrientation">
</select>
</div>
In my case the data.selectedOrientation is the default ng-model that i had to setup in the controller:
$scope.data.selectedOrientation = $scope.data.filters.basics.orientations[($scope.data.selections.basics.orientations[0]-1)]
If you dont want to change your dom element jsut add a ng-model to it
<tr ng-repeat="stockItem in stock | filter : stockFilter ">
<td>{{stockItem.dateCreated | date:'dd/MM/yyyy (HH:mm)'}}</td>
<td>{{stockItem.sku}}</td>
<td>
<select class="form-control">
<option ng-repeat="supplierOrderStock in stockItem.supplierStock | filter : supplierSelectionFilter" ng-modal="yourModelForThisDom"
value="{{supplierOrderStock.supplierId}}" >
£{{supplierOrderStock.price}}
</option>
</select>
</td>
</tr>
After learning a bit more I finally realised that it will be much easier if all the data is stored and filtered on the Model and collections within.
<select class="form-control" ng-show="stockItem.supplierStockFiltered.length > 0"
ng-model="stockItem.selectedSupplier"
ng-options="option as getSupplierDropDownText(option) for option in stockItem.supplierStockFiltered track by option.price"></select>
<span ng-show="stockItem.supplierStockFiltered.length == 0 || stockPackItem.supplierStockFiltered == null ">
No Stock
</span>
So when the data loads or when ever I click on any check boxes, I just use angular.forEach( in the controller to set the Selected Item based on what ever I filtered out. The actual two fields I am binding too are not contained int he the data that comes back from the server. But in JS you can just dynamically add those fields before the HTML binds and it works great!
The HTML is much cleaner and I have much better control over the models.
End of the day I had to go do this any way because now I need to save all the selected drop down values... and now because the Selected item is bound to the model.. its easy peasy. I just serialise the models and use the data on the server.

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

AngularJS: setting the previously selected option in the tag <select>

In the form I have a drop down list with multiple choice, as shown below. Elements are loaded from the database.
<label>Items</label>
<select class="form-control m-b"
ng-model="model.livingComplexId"
x-ng-change="updateOne(model.livingComplexId)">
<option></option>
<option ng-repeat="itemOne in itemsForAddrLevelOne"
value="{{itemOne.id}}">{{itemOne.tobName}}</option>
</select>
I make choose.
For example, I choose an item2.
Then save data. Then, I open the form to edit and I want to see an item that I chose, but the list is empty...
How can I set the previously selected value?
I would recommend to use the ngOptions directive to generate the select menu options:
<select ng-model="model.livingComplexId" ng-options="itemOne.id as itemOne.tobName for itemOne in itemsForAddrLevelOne"></select>
Maybe you could additionally change the ng-model value to model and use ng-options="itemOne as ..." (without the .id) and add an track by itemOne.id.
<select ng-model="yourModel" ng-options="itemOne.tobName for itemOne in itemsForAddrLevelOne"></select>
In the js you should set $scope.yourModel = itemsForAddrLevelOne[0];

Retrieve value that is stored in db and display in select box using angularjs and laravel

I am trying to retrieve a value that was stored in my MySQL database and display the selected value from the database along with the other select box items so that they can be updated. The problem that I am having is that the select box is not displaying the selected value that is stored in the database, instead it defaults to the empty first option. I am using angularjs to retrieve the values from laravel:
laravel
public function getEmployeeshifts() {
$employeeShift = DB::table('shift')
->select('shiftId', 'title')
->get();
return Response::json($employeeShift);
}
angularjs
$http.get('/schedule/employeeshifts').success(function(shiftdata) {
$scope.employeeshifts = shiftdata;
});
html
<select class="form-control input-sm" name="employeeshift"
ng-model="time.employeeshift"
ng-init="time.employeeshift='{{$schedules[0]->title}}'"
ng-options="employeeshift.title for employeeshift in employeeshifts track by employeeshift.shiftId" required>
<option value="">Select</option>
</select>
desired output
<option value="101">Shift A</option>
<option value="102">Shift B</option>
<option value="103">Shift C</option>
Based on the above desired output what i actually want to store in the database is the value but I need to show the words to the user. I am not sure what I am doing wrong, therefore I am asking for assistance to this problem.
AngularJS automatically resolves which item is selected based on the value of ng-model. It appears that you are setting the value of time.employeeshift to a title value and not a shiftId value. Try changing your ng-init attribute to time.employeeshift='{{$schedules[0]->id}}' or it's equivalent.
You have to set your model to the desired selected item. In your case, you are not setting it correctly in your ng-init. You should use employeeshift as your model.
<select ng-model="employeeshift"
ng-init="employeeshift = employeeshifts[0]"
ng-options="employeeshift.title for employeeshift in employeeshifts">
<option value="">Select</option>
</select>
This will bind the selected shift object to the $scope.employeeshift variable, and set the default value to the first object in your employeeshifts array.

Resources