Remove first value ? object:null ? in select option Angularjs - javascript

I'm having problems with select option in Angularjs
This is code in file js
$scope.ListOption = [];
$scope.ListOption.push({ Value: "0", Name: Car });
$scope.ListOption.push({ Value: "1", Name: House });
Here's what the code HTML looks like
<select class="form-control" id="Category" ng-model="Category">
<option ng-repeat="option in ListOption" value="{{option.Value}}">
{{option.Name}}</option>
</select>
The generated html is
<select class="form-control ng-pristine ng-valid" ng-model="Category" style="padding: 0px;">
<option value="? object:null ?"></option>
<option ng-repeat="option in ListOption" value="0" class="ng-binding ng-scope">Car</option>
<option ng-repeat="option in ListOption" value="1" class="ng-binding ng-scope">House</option>
</select>
I have quite a headache on this issue. Looking forward to having someone help me the other way

AngularJs tend to do this (generate extra option elment) when the value of the variable in ng-model doesn't match any of the values of the existing <option>.
You can solve it by setting an initial value (of the same type also), and it's one of the values in your <option> elements .
Or add one <option> element without value and with text Select one inside it. so it'll be selected.
function MyController($scope) {
$scope.Category = "1";
$scope.ListOption = [];
$scope.ListOption.push({ Value: "0", Name: 'Car' });
$scope.ListOption.push({ Value: "1", Name: 'House' });
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyController">
<select class="form-control" id="Category" ng-model="Category"
ng-options="item.Value as item.Name for item in ListOption">
</select>
{{Category}}
</div>
Make sure $scope.Category is the same type (not only value) as Value in ListOption variable, otherwise AngularJs will create extra option and select it.

The first option
<option value="? object:null ?"></option>
is generated because the ngModel value Category is not defined and select will match the value of Caegory with its options. Since no option is undefined, it adds a dummy option itself.
To solve this yyu can initialize the ngModel value Category to the first option automatically or add a new option with value as blank string and then initialize Category to blank string. It will also trigger your validation if any.
New options would be
$scope.Category = "";
$scope.ListOption = [];
$scope.ListOption.push({ Value: "", Name: "Please Select" });
$scope.ListOption.push({ Value: "0", Name: "Car" });
$scope.ListOption.push({ Value: "1", Name: "House" });
Hope it helps.

As you wanted to mention the first value as default you can use ng-selected in option to set 0 as default. Below mentioned code sample for your reference.
<select class="form-control" id="Category" ng-model="Category">
<option ng-repeat="option in ListOption" value="{{option.Value}}" ng-selected="option.Value == '0'">
{{option.Name}}</option>
</select>

Related

Remove selected option from drop down in Angular

I have a button which adds more select drop downs when clicked. So I would like to remove the already selected options in these select boxes for preventing duplication.
The following code is used for the select drop down:
<select class="select form-control"
formControlName="environment_id" (change)="onEnvChange($event.target.value)">
<option selected="selected" disabled value="">Select Environment
</option>
<ng-container *ngFor="let environment of environments">
<option *ngIf="!selectedEnvironments.includes(environment.environment_id)"
[value]="environment.environment_id">
{{environment.environment_id}}</option>
</ng-container>
</select>
and in the component I ave the following function for change
public onEnvChange(selectedEnvironment)
{
this.selectedEnvironments.push(selectedEnvironment);
}
Now when I select an option, that option itself gets removed from the dropdown. For example if I have options like option1,option2,option3 etc, when I select option1, option1 is getting removed from the dropdown. How to fix this and remove the option only for the next select dropdown ?
You can try create two objects of environments and listen selection with valueChanges from formControl. After you get the selected environmentid and filter the other object without this id
Example
ngOnInit(){
this.createForm();
this.getEnvironments();
this.environmentChanges()
}
createForm(){
this.form = this.fb.group({
'environment_id_1': [''],
'environment_id_2' : ['']
})}
getEnvironments(){
const environments = [
{ 'environment_id': 1, 'environment': 'A' },
{ 'environment_id': 2, 'environment': 'B' },
{ 'environment_id': 3, 'environment': 'C' },
{ 'environment_id': 4, 'environment': 'D' }];
this.environments1 = environments;
this.environments2 = environments;}
environmentChanges(){
this.form.controls['environment_id_1'].valueChanges
.subscribe((environment_id)=>{
this.environments2 = this.environments1.filter((env)=> env.environment_id != environment_id)
})}
<form [formGroup]="form">
<div class="row">
<select class="select form-control" formControlName="environment_id_1">
<option value="">Select Environment 1 </option>
<option *ngFor="let environment of environments1" [value]="environment.environment_id"> {{environment.environment}} </option>
</select>
</div>
<div class="row" style="padding-top: 10px;">
<select class="select form-control" formControlName="environment_id_2">
<option value="">Select Environment 2 </option>
<option *ngFor="let environment of environments2" [value]="environment.environment_id"> {{environment.environment}} </option>
</select>
</div>
enter image description here

ng-options not populating select options drop down

Hello I have tried implementing the changes provided in several examples yet none seem to work. I do have an ng-model and I clearly define the property of the object I would to receive. However it still does not work.
Any help would be great.
HTML
<select chose ng-model="selected" ng-options="type as type.Name for type in ansExplanOpt">
<option value="">-- Select an Option --</option>
</select>
Controller
$scope.selected = ansExplanOpt.data;
The object is populating (I checked) and the properties it has are Name and Id.
Any help would be great. Thanks
You were very close. Just looks like a misuse of the ng-model value. Your code should be something like
<select chose ng-model="selectedValue" ng-options="type.Id as type.Name for type in ansExplanOpt">
</select>
And the ng-model will be what the user has selected.
Their documentation breaks it down well also:https://docs.angularjs.org/api/ng/directive/ngOptions
Here is solution:
ng-model is the value that user selected.
function TodoCtrl($scope) {
$scope.ansExplanOpt = [
{text:'learn angular', id:1},
{text:'build an angular app', id:2}];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
<select chose ng-model="select" ng-options="type as type.text for type in ansExplanOpt">
<option value="">-- Select an Option --</option>
</select>
{{select.text}}
<br>
{{select}}
</div>
</div>
You can define which element in the array you want to be preselected:
var myApp = angular.module('myApp', [])
.controller('TestController', ['$scope', function($scope) {
$scope.data = [{
label: 'blah',
value: 'blah'
}, {
label: 'blah1',
value: 'blah1'
}, {
label: 'blah2',
value: 'blah2'
}];
$scope.sel = $scope.data[0];
}]);
html:
<div ng-controller="TestController">
{{sel}}
<select ng-model="sel.value" ng-options="d.value as d.label for d in data">
</select>
</div>
See jsfiddle for more details

Select element value is not binding because of type mismatch in angularjs 1.4

I am using a ng-model and it is assigned a value but it is not binding with selected element.
<select data-ng-model="myval">
<option value="? number:2 ?"></option>
<option value="2" class="ng-binding">Value 1</option>
<option value="3" class="ng-binding">Value 2</option>
</select>
in the above code snippet number:2 is generated because myval is assigned to 2 and
I noticed that it is because of type mismatch. My question is how will we give value in option tag with type number?
Thanks in advance.
I always use the ng-options directive instead of a custom select with an ng-repeat and many ng-value
If you have something like this :
$scope.items = [
{ id: 1, title: 'key #1' },
{ id: 2, title: 'key #2' }
];
Then you should do :
<select ng-model="selected" ng-options="item.title for item in items"></select>
You will get :
<select ng-model="selected" ng-options="item.title for item in items">
<option value="key #1"></option>
<option value="key #2"></option>
</select>
And the binding will allow you to do :
console.log($scope.selected); // { id: 2, name: 'key #2' }
You can find an example here : http://codepen.io/anon/pen/GpKKaW

AngularJS ng-model not setting correct value

I have a table and when clicking on a row I call this function:
$scope.updateRow = function(row) {
$scope.row = angular.copy(row);
}
$scope.row has a name attribute and I have a select menu that should display this name:
<select name="rowName" ng-model="row.name" required required-message="'A name must be selected '" class="sa-select">
<option value=""></option>
<option ng-repeat="name in names" value="{{name.fullName}}">{{name.fullName}}</option>
</select>
However when clicking the row it sets the option value in the select menu to
<option value="? string:test name ?"></option>
even though $scope.row.name = "test name"
The option value should look like:
<option value="test name">test name</option>
Seems to be a similar issue to this question: Angular adds strange options into select element when setting model value
<select name="rowName" ng-options="name.fullName as name.fullName for name in names" ng-model="row.name" required required-message="'A name must be selected '" class="sa-select">
Not tested tho, but you can read more here: https://docs.angularjs.org/api/ng/directive/ngOptions
And if you would want to add a default option it would look like this:
<select name="rowName" ng-options="name.fullName as name.fullName for name in names" ng-model="row.name" required required-message="'A name must be selected '" class="sa-select">
<option value="your value"> your text </option>
</select>

Angular JS select with manual options

We have some drop downs in our app that we can NOT use ng-options with because we need to set the title attribute on the <options> tag itself which is not possible with ng-options.
The reason we need the title is because IE < 9 chops off values that are to long and they are only visible with the title(shows up on hover of the element)
Now, to see the issue I'm having look at the following JS fiddle.
http://jsfiddle.net/nstuart/nF7eJ/
(HTML Bit)
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-model="params.value">
<option value="">Any</option>
<option ng-repeat="v in options" value="{{v.value}}" title="{{v.name}}" ng-selected="{{v.value == params.value}}">{{v.name}}</option>
</select>
<p>{{params.value}}</p>
</div>
Ideally the select would have 'test3' selected, but you can see it gets set to an empty option instead. I understand this is from the fact that the value of ng-model is not present in the ng-options, but thats because I have not defined one!
Any ideas on how to get something like this working? Possibly even be able to add title to the options generated by ng-options so we could use that instead?
EDIT
Updated the fiddle at: http://jsfiddle.net/nstuart/nBphn/2/ to as described in the answer below.
Actually, just remove the curly braces from the expression in ng-selected and it will work:
<option ng-repeat="v in options"
value="{{v.value}}"
title="{{v.name}}"
ng-selected="v.value == params.value">{{v.name}}
</option>
fiddle
<option ng-repeat="v in options" value="{{v.value}}" title="{{v.name}}"
ng-selected="checkOption(v.value)">{{v.name}}</option>
$scope.checkOption = function(value){
return($scope.params.value == value);
}
Fiddle
[UPDATE] forgot to pass value variable. Updated fiddle and answer.
For manual options, you only need to use ng-model directive. This ng-model directive gives two way data binding for the selected option.
jsfiddle: http://jsfiddle.net/rpaul/1p9b5et8/1/
<body ng-app ng-controller="AppCtrl">
<select ng-model="selectedFruit" >
<option value ='1'> Apple</option>
<option value ='2'> Orange</option>
</select>
Selected value is {{selectedFruit}}
</body>
function AppCtrl($scope) {
$scope.selectedFruit = '1';
}
You might also want to take a look at the select2 directive in http://angular-ui.github.com/#directives-select2
In my code, I re-calculate select title on ng-change="changeItem()"
HTML
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-options="item.id as item.title for item in items"
ng-model="selectedId" ng-change="changeItem()" title="{{myTitle}}">
<option value="" disabled selected style="display: none;">Select Item</option>
</select>
<div>
{{selectedId}}
</div>
<div>
{{myTitle}}
</div>
</div>
app.js
angular.module('myApp', []);
function MyCtrl($scope) {
$scope.items = [{
id: 1,
title: "Icebox"
}, {
id: 2,
title: "Summer"
}, {
id: 3,
title: "Milestone"
}];
$scope.changeItem = function() {
$scope.myTitle = undefined;
for(var i=0; i<$scope.items.length; i++){
if($scope.items[i].id == $scope.selectedId){
$scope.myTitle = $scope.items[i].title;
}
}
}
}
Fiddle

Categories

Resources