Select default value at ng-options - javascript

I have this code and information:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
$scope.selected = 2;
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
</select>
However, the options are created like this:
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
<option value="0">My label</option>
<option value="1">My label 2</option>
</select>
How can I set the selected option to My label 2? I know it can be done:
$scope.selected = $scope.options[1];
But my problem is that option is created in a directive, and at that moment I don't know 1) how many values has $scope.options, nor 2) what is the index of the selected option in database. The only thing I know is the id (which is in the object).
The html of my directive is something like this:
<select ng-switch-when="select" ng-model="form.model[element.model]" ng-options="{{element.rule}}"></select>
Where element.rule is:
rule: "role.role for role in element.options"
And element.options has the array with options, and form.model[element.model] has the id of the option selected.
How can I get the index of the element with ID X in the array $scope.options? I'm very sure that will give me the solution, but I don't know how to do it...

Just set the correct model value when initiating the controller. You can easily get the correct array value if you know the ID by using a filter:
$scope.selected = $filter('filter')($scope.options, {id: 2})[0];

The issue with your code as I see it is that the 'selected' value coming out of your database is the ID of the object selected and not the object itself. This is fine but because of that difference you can't simply set
$scope.selected = 2 //assuming 2 is the value coming from your database
because the value '2' does not exist in your option array. The Object with an ID of 2 does.
If you can always guarantee the options you have in the option array are from 1-n and in that order, you can accomplish this by simply using this instead:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
var selectedIdFromDatabase = 2;
$scope.selected = $scope.options[selectedIdFromDatabase-1];
If you can't make that guarantee (and even if you can for now, it may not be a good idea to make that assumption in your code) you'll need iterate over the array of objects you have to identify the object with an ID of the selectedId from your database.
The answer to this question has a great write-up about the type of data-processing you'll need to do and a lot more information about javascript objects in general.

Related

Bind options value to ng-model in angularjs

I'm working on a project, and I need to bind the options value to object key's in such a manner that, on selecting an option, it gives 1, else other variables remain 0.
My HTML Code:-
<select required class="custom-select">
<option disabled>Select an option</option>
<option ng-model="PredictCtrl.detail.building_type_AP">Apartment</option>
<option ng-model="PredictCtrl.detail.building_type_GC">Independent House / Villa</option>
<option ng-model="PredictCtrl.detail.building_type_IF">Independent Floor / Builder's Floor</option>
<option ng-model="PredictCtrl.detail.building_type_IH">Gated Community Villa</option>
</select>
Variable to bind -
PredictCtrl.detail = {
building_type_AP: 0,
building_type_GC: 0,
building_type_IF: 0,
building_type_IH: 0
}
Generally, binding is done with select tag, which gives the value of the selected option, but I want in such a way that, when I click on Apartment option, it's bind variable PredictCtrl.detail.building_type_AP becomes 1, rest remains 0. Similarly, it does with other options.
I want to send the data as the same format through API.
So, please Help me out.
Sorry If I was not very clear with explaining or for any typo.
Thank you in advance.
You should take a look at the NgOptions directive which is the "angularjs" way of working with the select-tag.
It sould be able to fulfill your requirement as you will get the selected option in the SelectedOption object.
Here's an example
angular.module("app",[]).controller("myCtrl",function($scope){
$scope.details =
[
{name:"Apartment", value:1},
{name:"Independent House / Villa", value:2},
{name:"Independent Floor / Builder's Floor", value:3},
{name:"Gated Community Villa", value:4}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select required class="custom-select" ng-options="item as item.name for item in details" ng-model="selectedOption">
</select>
<p>SelectedOption: {{selectedOption}}</p>
</div>
None of the answers at my time of writing actually present a functioning solution, so here's one.
Don't scatter ng-model directives across different option elements, it's unnecessary.
You can achieve what you want by using ng-options to enumerate all your choices, a single ng-model to keep track of the selected option, and ng-change to apply the values as you described (i.e. 1 on the selected key, 0 for everything else).
I've assumed you've got a requirement to keep the structure of detail as is. If it can be changed, then I'd recommend associating each labels with each it's respective building_type_ to keep things together.
See below.
angular
.module('app', [])
.controller('PredictCtrl', function () {
this.selectedDetail = null;
this.detail = {
building_type_AP: 0,
building_type_GC: 0,
building_type_IF: 0,
building_type_IH: 0,
};
this.labels = {
building_type_AP: 'Apartment',
building_type_GC: 'Independent House / Villa',
building_type_IF: 'Independent Floor / Builder\'s Floor',
building_type_IH: 'Gated Community Villa',
};
this.changeDetail = function () {
for (var key in this.detail) {
this.detail[key] = +(this.selectedDetail === key);
}
};
});
<script src="https://unpkg.com/angular#1.7.4/angular.min.js"></script>
<div ng-app="app" ng-controller="PredictCtrl as PredictCtrl">
<select
ng-model="PredictCtrl.selectedDetail"
ng-options="key as PredictCtrl.labels[key] for (key, value) in PredictCtrl.detail"
ng-change="PredictCtrl.changeDetail()"></select>
<pre>{{ PredictCtrl.detail | json }}</pre>
</div>
try like this:
in your controller:
$scope.details = [
{
name: "building_type_AP",
value: "Apartment",
state: false
},{
name: "building_type_GC",
value: "Independent House / Villa",
state: false
}/*add more here*/
];
$scope.setActive = function(detail){
detail.state = !detail.state;
}
in html template:
<select required class="custom-select">
<option disabled>Select an option</option>
<option ng-repeat="detail in details" ng-click="setActive(detail)">{{detail.value}}</option>
</select>
in the end just go through $scope.details and parse false to 0 and true to 1 OR just do this inside setActive function

vue select doesn't show initial value

I am trying to show the initial value of a array of objects like this:
tableStyes[
{Id: 1, style: "blabla1},
{Id: 2, style: "blabla2"}
]
basicly i am using a computer method to give me the array from vuex store
tableStyles () {
return this.$store.getters.getTableStyles
},
i am doing the select this way:
<select class="form-control" v-model="table.tableStyle">
<option v-for="(item,key) in tableStyles" :value="item.Id">
{{ item.style }}
</option>
</select>
i want to get the value based on the id, i mean i want to get the text associated to the id, and the id is table.tableStyle, that is 1 at the begin that should be the selected item, but somehow it doesn't work :/.
Any help?
You need no computed method to display data from vuex store.
v-model="table.tableStyle" sets the first displayed item, if it is initialized with anything that is not included in the array, no item will be selected before you select one manually.
Try:
data:{
return {
...
table.tableStyle: this.$store.getters.getTableStyles[0]
}
}
I dont know if this works in data section.

Angular iterate through select options and set selected value

I have a select set with States from JSON data:
<select name="ParentState" ng-model="selectedState" ng-options="s.StateID as s.StateCode for s in cStates | orderBy:'StateCode'">
<option value="">Select State...</option>
</select>
and would like to set the selected state as the state returned for the logged in user but I'm entirely sure how to accomplish this in Angular. Here's what I've tried and it isn't working.
angular.forEach($scope.cState, function (s) {
if (s.StateCode == xParentState) {
$scope.selectedState = s.StateCode;
}
});
xParent is this state initials e.g. 'MI' for Michigan
The ngModel is set to the StateID (as seen in your ngOptions - value as text for object in array) - so set that rather than StateCode
if (s.StateCode == xParentState) {
$scope.selectedState = s.StateID;
}
Check the documentation for `ngOptions.
You're using the select as label for value in array expression here. So to set the ngModel, you will need to set the StateID.
Assuming you have an object like:
xParentState: {
StateID: 1,
StateCode: 'MI',
StateName: 'Michigan'
}
Instead of iterating over the array of states, you can then set the value directly with $scope.selectedState = xParentState.StateID or you could use ngInit for setting it in the template (e.g. when the user reloads the page):
<select ng-model="selectedState" ng-options="s.StateID as s.StateCode for s in cStates | orderBy:'StateCode'" ng-init="selectedState = xParentState.StateID">
<option value="">Select State...</option>
</select>

ngOptions weird behavior when trying to use resource response as selected item

I tried to solve this over an hour, haven't found anything online.
This is the template:
<select
ng-model="user.platform_id"
ng-options="platform.id as platform.title for platform in platforms"
id="platform_id" class="form-control">
</select>
and this is the controller :
$scope.platforms = platformsEntity.query();
// Resource object coming from UI Router resolve, already fetched with user info
$scope.user = userEntity;
the platforms resource response return the following format:
[ { id: 4, title: 'platform1'}, { id: 5, title: 'platform2' ]
the user is same, resource object with platform ID
{ id: 3, name: 'foo', platform_id: 5 }
This way I can see all the platforms in the select box but it's not getting selected by the ngModel value (user.platform_id)
The thing is that when I use plain object instead of resource:
$scope.platforms = platformsEntity.query();
$scope.user = { platform_id: 5 } ;
It is getting selected correctly ...
Update
i replicated the behavior i am looking for in ng-repeat:
<select ng-model="user.platform_id" id="platform_id" class="form-control">
<option
value="{{ platform.id }}"
ng-selected="user.platform_id == platform.id"
ng-repeat="platform in platforms"
>{{ platform.title }}</option>
</select>
It's not about using a resource, the problem with programmatic selection of ng-options is that the ng-model value should refer to the same object as in the ng-options. In order to initialize the selection, first make sure that the platforms array is populated (query might be async?), then loop through them, and set the id object of the platform of your choice as the platform_id object of the user.
Try something like this. Tell angular what you want to track the value by.
<select
ng-model="user.platform_id"
ng-options="platform.title for platform in platforms track by platform.id"
id="platform_id" class="form-control">
</select>

angularjs - remove option from input select

Can't figure this out for the life of me. Using AngularJS.
I have a dropdown Select field with several options. It is a part of a form that may be completed multiple times (ie "add another" type form). Now, one of the options may only be used once. How can I remove this option from all other select fields after it has been used?
What I'm working with:
html
<select ng-model="item.itemtype">
<option ng-repeat="i in itemtype" value="{{i}}" ng-init="item.itemtype = itemtype[0]">{{i}}</option>
</select>
angularjs
$scope.Items = [
{ 'itemtype': '', 'desc': '', 'color': '' }
];
$scope.itemtype = [
'shirt',
'pants',
'hats',
'shoes',
'special'];
What I've tried (and really doesn't work)
$scope.specialremove = function() {
var exist = Items.indexOf("special")
if (exist !== 0) {
return '';
}
else {
return 'special';
}
}
I'm hoping I don't have to turn to any other framework to solve this. Feel free to point out any other problems/errors/inefficiencies in my code.
The first thing that can help is using ng-options:
ng-options="type for type in itemType".
It would be better to have objects with label and value properties, in order to write it as
ng-options="type.value as type.label for type in itemType"
and separate the displayed label from the actual value of the selection.
In your controller you should have something like:
$scope.itemType= [
...
];
$scope.selectedItem= $scope.itemType[0];
So that you can write the select as:
<select ng-Model="selectedItem" ng-options="item.value as item.label for item in itemType"></select>
To remove a selected item you can watch the value of selectedItem in the controller: when it matches the value you want, remove it from the array and update selectedItem accordingly.
Here is a basic fiddle. I simply remove the third option after selecting it, and reset the selected item to the first.

Categories

Resources