In AngularJS, how to change the default option of a select? - javascript

I am using AngularJS. There are two select, the first is the "team select," the second is the "member select." If the "team select" have the members, the "member select" show " select the member ." If the "team select" don't have the members, the 'member select" show "no member."
My problem is how to change the default option of the "member select".
This is my code:
<script src="angular.js"></script>
<div class="bigDiv">
<select class="common_select" name="xxx" ng-options="item as item.teamname for item in team_array" ng-model="select_team" id="" ng-change="selectMemberFun(select_team)">
<option value="" disabled selected hidden>select a team</option>
</select>
<select class="common_select" name="xxxxx" id="" ng-options="item as item.name for item in select_team.members" ng-model="select_member">
<option ng-show="!have_member" value="" disabled selected hidden>no member</option>
<option ng-show="have_member" value="" disabled selected hidden>select a member</option>\
</select>
</div>
<script src="angular.js"></script>
<script>
angular.module('app',[]).controller('xxx',['$scope', function ($scope) {
$scope.have_member = false;
$scope.team_array = [
{teamname: "team1", members:[ {name:'team1member1'}, {name:'team1member2'}]},
{teamname: "team2", members:[ {name:'team2member1'}, {name:'team2member2'}]},
{teamname: "team3", members:[]},
];
$scope.selectMemberFun = function (team) {
if(team.members.length == 0){
$scope.have_member = false;
} else {
$scope.have_member = true;
}
}
}])
</script>
Why does the 'ng-show' directive not work ? The "member select" always shows "no member".

I've tried a few ways, looks like this one works.
angular.module('app', []).controller('TestController', ['$scope',
function($scope) {
$scope.have_member = false;
$scope.team_array = [{
teamname: "team1",
members: [{ name: 'team1member1' }, { name: 'team1member2' }]
}, {
teamname: "team2",
members: [{ name: 'team2member1' }, { name: 'team2member2' }]
}, {
teamname: "team3",
members: []
}, ];
$scope.selectMemberFun = function(team) {
if (team.members.length == 0) {
$scope.have_member = false;
} else {
$scope.have_member = true;
}
}
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div class="bigDiv" ng-app="app" ng-controller="TestController">
<select class="common_select" name="xxx" ng-options="item as item.teamname for item in team_array" ng-model="select_team" id="" ng-change="selectMemberFun(select_team)">
<option value="" disabled selected hidden>select a team</option>
</select>
<select class="common_select" name="xxxxx" id="" ng-options="item as item.name for item in select_team.members" ng-model="select_member">
<option value="" disabled selected hidden>{{have_member ? 'select a member' : 'no member'}}</option>
</select>
</div>

According to the documentation -> https://docs.angularjs.org/api/ng/directive/select
<select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
<option value="">---Please select---</option> <!-- not selected / blank option -->
<option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
<option value="option-2">Option 2</option>
</select>

It doesn't work because ngOptions is like ngReapeat in that it will ONLY iterate when there are values in the select_team.members array. In Team3 the member array is empty, so all the inner <option></option> are skipped.

Related

dynamic item selection of product and price

I'm having a list of items in an array with its prices. The list of items must be displayed in a dropdown. When one is selected, I want its corresponding price to be placed into a text box called price.
JS:
function PopulateDropDownList() {
var products = [
{ productId: 1, name: "Fanta", price: "4" },
{ productId: 2, name: "Coke", price: "2" },
{ productId: 3, name: "Sprite", price: "8" },
{ productId: 4, name: "Malta Guniness", price: "10" }
];
}
HTML:
<body onload="PopulateDropDownList()">
<hr />
<select id="productsDropDown">
</select>
<input type="text" name="price" value="">
</body>
I think you are trying something like below-posted code.
function myFunction(e) {
document.getElementById("price").value = e.target.value
}
<hr />
<select id="productsDropDown" name="productsDropDown" onchange="myFunction(event)">
<option value="4">productId: 1</option>
<option value="2">productId: 2</option>
<option value="8">productId: 3</option>
<option value="10">productId: 4</option>
</select>
<input type="text" size="30" name="price" id="price" />
var demo = angular.module('demo', []);
function MyCtrl ($scope) {
$scope.myGroups = [
{label:'Admin', value:1},
{label:'Users', value:2},
{label:'Public', value:3}
];
$scope.tellUs = function() {
console.log("the selected group is - " + $scope.group);
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div ng-app='demo' ng-controller='MyCtrl'>
<p>You've just selected {{group}}.</p>
<form>
<select ng-model="group"
ng-options="o.value as o.label for o in myGroups"
ng-change="tellUs()"/>
</form>
</div>

Set default value of a dropdown and reset it in AngularJS

So there is a dropdown selector which must be set on the default option and be able to reset to it if reset button is clicked.
I managed to do it with jQuery, I'm wondering how can it be done using AngularJS
$('#buttonID').click(function(){
$('#selectId').val('0');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="selectId">
<option value="0">first option</option>
<option value="1">second option</option>
<option value="2">third option</option>
</select>
<input type="button" id="buttonID" value="reset"/>
Any suggestions?
You need to have a collection of options and a model bound to the select box. On reset, you just need to change the value of bound model to what you want:
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.opt = 0;
$scope.options = [{
value: 0,
label: 'first option'
}, {
value: 1,
label: 'second option'
}, {
value: 2,
label: 'third option'
}];
$scope.reset = function() {
$scope.opt = 0;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select id="selectId" ng-options="opt.value as opt.label for opt in options" ng-model="opt">
</select>
<input type="button" id="buttonID" value="reset" ng-click="reset()"/>
</div>

Angular 2 changing disabled/enabled select options

I'm using Angular2 and I have 2 selects:
<div ng-controller="ExampleController">
<form name="myForm">
<label for="companySelect"> Company: </label>
<select name="companySelect" id="companySelect">
<option *ngFor="let company of companies"
value="{{company.id}}"> {{company.name}}
</option>
</select>
<label for="documentTypeSelect"> Type: </label>
<select name="documentTypeSelect" id="documentTypeSelect">
<option value="type1">type1</option>
<option value="type2">type2</option>
<option value="type3">type3</option>
</select>
</form>
<hr>
</div>
I want to change second select options depending on the first select. I can get types (boolean value) by using
company.companyRelations.pop().type1
company.companyRelations.pop().type2
And now, if for example type1 is false, the option in second select should be disabled and if type2 is true, option should be enabled. Is that possible?
EDIT:
Companies in select have deasdv, invoic and orders properties which are true or false. How can i now pass these properties into component.ts properties? Is it possible by event or what? I want to get for example
company.companyRelations.pop().desadv
For company which is selected and it will change disabled options in the second one.
html
<form name="myForm">
<label for="companySelect"> Company: </label>
<select class="form-control" name="companySelect" id="companySelect"
[(ngModel)]="companySelect" (ngModelChange)="onChange($event)">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option *ngFor="let company of companies" [ngValue]="company.id">
{{company.name}}</option>
</select>
<select name="documentTypeSelect" id="documentTypeSelect">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option [disabled]="!desadv" value="desadv">desadv</option>
<option [disabled]="!invoic" value="invoic">invoic</option>
<option [disabled]="!orders" value="orders">orders</option>
</select>
</form>
component.ts
desadv: boolean = false;
invoic: boolean = false;
orders: boolean = false;
and here it will be something like:
onChange(event) {
if(event.desadv) {
this.desadv = true;
}
}
My solution:
html
<form name="myForm">
<label for="companySelect"> Company: </label>
<select name="companySelect" id="companySelect" [(ngModel)]="companySelect"
(ngModelChange)="onChange($event)">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option *ngFor="let company of companies" [ngValue]="company">
{{company.name}}</option>
</select>
<label for="documentTypeSelect"> Type: </label>
<select name="documentTypeSelect" id="documentTypeSelect">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option [disabled]="!desadv" value="desadv">desadv</option>
<option [disabled]="!invoic" value="invoic">invoic</option>
<option [disabled]="!orders" value="orders">orders</option>
<option [disabled]="!recadv" value="orders">recadv</option>
<option [disabled]="!shipment" value="orders">shipment</option>
</select>
component.ts
onChange(event) {
this.desadv = event.companyRelations[0].desadv;
this.invoic = event.companyRelations[0].invoic;
this.orders = event.companyRelations[0].orders;
this.recadv = event.companyRelations[0].recadv;
this.shipment = event.companyRelations[0].shipment;
}
Try this :
<select class="form-control" name="companySelect" id="companySelect" [(ngModel)]="companySelect" (ngModelChange)="onChange($event)">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option *ngFor="let company of companies" [ngValue]="company.id">{{company.name}}</option>
</select>
<select [disabled]="btnDisable" name="documentTypeSelect" id="documentTypeSelect">
<option value="type1">type1</option>
<option value="type2">type2</option>
<option value="type3">type3</option>
</select>
component.ts
private companySelect: any;
private btnDisable: boolean = true;
onChange(event) {
if(event) {
this.btnDisable = false;
}
}
Yes it is possible.
I have created a demo in which second drop down will be enabled depending upon the value of flag in first drop down object.
// Code goes here
var myApp = angular.module('plunker',[]);
angular.module('plunker').controller('MyCtrl', MyCtrl)
MyCtrl.$inject = ['$scope'];
function MyCtrl($scope) {
$scope.items1 = [{
id: 1,
label: 'aLabel',
'flag':true,
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
'flag':false,
subItem: { name: 'bSubItem' }
}];
$scope.items2 = [{
id: 1,
label: 'MyName',
'flag':true,
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'YourName',
'flag':false,
subItem: { name: 'bSubItem' }
}];
$scope.changeDetect = function(){
$scope.selected1='';
console.log($scope.selected);
if($scope.selected.flag)
{
$scope.flagValue=false;
} else {
$scope.flagValue=true;
}
}
$scope.flagValue=true;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MyCtrl">
<select ng-options="item as item.label for item in items1 track by item.id" ng-model="selected" ng-change="changeDetect()"></select>
<select ng-options="item as item.label for item in items2 track by item.id" ng-model="selected1" ng-disabled="flagValue"></select>
</div>
In AngularJS 2
<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
<option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
<select [ngModel]="selectedDeviceObj1" name="sel2" [disabled]="flag">
<option [ngValue]="i" *ngFor="let i of deviceObjects1">{{i.name}}</option>
</select>
onChangeObj(newObj) {
this.selectedDeviceObj1='';
console.log(newObj);
this.selectedDeviceObj = newObj;
if(newObj.flag){
this.flag = false;
}
else {
this.flag = true;
}
Please find Demo Link Plunkr

Select option doesnt bind with ng-model

I have an object with AllCountries and SelectedCoutry.
I want to list all countries on a <select> and select the option with ng-model by the value of SelectedCountry.
But the default value of combobox gets selected null.
Example:
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.OBJ = {
"OBJ": {
"AllCountries": [
{
"country": "USA",
"id": 1
},
{
"country": "Mexico",
"id": 2
},
{
"country": "Canada",
"id": 3
}
],
"SelectedCountry": {
"country_id": 1,
}
}
}
$scope.AM = $scope.OBJ.OBJ;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ngPatternExample">
<div ng-controller="ExampleController">
selected country: {{AM.SelectedCountry.country_id}} <br/>
<select class="form-control" ng-model="AM.SelectedCountry.country_id">
<option value=""> --- </option>
<option ng-repeat="co in AM.AllCountries" value="{{co.id}}"> {{co.country}} </option>
</select>
</div>
</body>
(http://plnkr.co/edit/PI3tOrIMSTMwGC0rYA5q?p=preview)
p.s A good explanation why this doesnt work allways in Angular would be great
Replace your select with this
<select class="form-control" ng-options="co.id as co.country for co in OBJ.OBJ.AllCountries" ng-model="AM.SelectedCountry.country_id">
<option value=""> --- </option>
</select>
Use ngOptions directive instead of repeating options in the select box by yourself.
<select
class="form-control"
ng-model="AM.SelectedCountry.country_id"
ng-options="co.id as co.country for co in AM.AllCountries">
<option value=""> --- </option>
</select>
Updated plunk:
http://plnkr.co/edit/FZcJVkJQlbLM3k544s8S?p=preview

Disable optgroup of multiple select which has specific label

I have taken a select list with multiple option using ng-options. I am using it as below:
<select ng-options="c as c.Text for c in ReceiverList track by c.Value" ng-model="ReceiverUserID" class="form-control" id="ddlReceiverUserID" ng-change="GetWorkers(ReceiverUserID, SenderUserID,'receiver')">
<option value="">--Select Supervisor--</option>
</select> <!-- Parent Drop Down-->
<select multiple ng-options="c as c.Text group by c.Group
for c in receiveList track by c.Value" ng-model="Workers"
class="form-control" id="ddlWorkers" size="10">
</select> <!-- Child Drop Down -->
This select dropdown get filled when I select some item from another dropdown.(It's a kind of cascaded dropdown). Filling it like below:
$scope.GetWorkers = function (objA, objB, ddlType) {
$http.post("user/Workers/", { userID: objA.Value })
.success(function (data, status, headers, config) {
if (ddlType == 'sender') {
$scope.sendList = data;
} else {
$scope.receiveList = data;
$('#ddlWorkers optgroup[label="Current Users"] option').prop('disabled', true); // Not working
}
})
.error(function (data, status, headers, config) {
showToast(ToastType.error, "Error occured while fetching workers.", "Failure");
});
}
I want to disable child dropdown's specific group items. So I tried below code but it is not working:
$('#ddlWorkers optgroup[label="Current Users"] option').prop('disabled', true);
I don't know how do I disable specific group items of select whenever its data changes or new data loaded.
Here is HTML output in which I want to disable all optgroup[label="Current Users"] members:
<select multiple="" ng-options="c as c.Text group by c.Group for c in receiveList track by c.Value" ng-model="Workers" class="form-control ng-pristine ng-valid" id="ddlWorkers" size="10">
<optgroup label="Current Users">
<option value="4118">Kevins Numen</option>
<option value="4119">ggdfg fdgdfg</option>
</optgroup>
<optgroup label="New Users">
<option value="1093">Case Worker</option>
</optgroup>
</select>
I don't know much about angularjs or ng-options, but it seems that everybody else used some timeout to let the process populate the received data to the input, and you can try something this like others:
...
} else {
$scope.receiveList = data;
setTimeout(function(){
$('#ddlWorkers optgroup[label="Current Users"] option')
.prop('disabled', true); // Not working
}, 100);
}
...
maybe not similar but good to have a look here:
is there a post render callback for Angular JS directive?
You need to customize your code and also JSON Object
<div ng-controller="AjaxCtrl">
<h1>AJAX - Oriented</h1>
<div>
Country:
<select id="country" ng-model="country" ng-options="country for country in countries">
<option value=''>Select</option>
</select>
</div>
<div>
City: <select id="city" ng-disabled="!cities" ng-model="city"><option value='' ng-repeat="item in cities" ng-disabled="item.disabled">{{item.name}}</option></select>
</div>
<div>
Suburb: <select id="suburb" ng-disabled="!suburbs" ng-model="suburb" ng-options="suburb for suburb in suburbs"><option value='' ng-disabled="item.disabled" ></option></select>
</div>
</div>
Your Angular
function AjaxCtrl($scope) {
$scope.countries = ['usa', 'canada', 'mexico', 'france'];
$scope.$watch('country', function(newVal) {
if (newVal)
$scope.cities = [
{ id: 1, name: '11111'},
{ id: 2, name: '22222', disabled: true },
{ id: 3, name: '33333', disabled: true }
]
});
$scope.$watch('city', function(newVal) {
if (newVal) $scope.suburbs = ['SOMA', 'Richmond', 'Sunset'];
});
}
function AjaxCtrl($scope) {
$scope.countries = ['usa', 'canada', 'mexico', 'france'];
$scope.$watch('country', function(newVal) {
if (newVal)
$scope.cities = [
{ id: 1, name: '11111'},
{ id: 2, name: '22222', disabled: true },
{ id: 3, name: '33333', disabled: true }
]
});
$scope.$watch('city', function(newVal) {
if (newVal) $scope.suburbs = ['SOMA', 'Richmond', 'Sunset'];
});
}
<link href="http://fiddle.jshell.net/css/normalize.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<div ng-controller="AjaxCtrl" class="ng-scope">
<h1>AJAX - Oriented</h1>
<div>
Country:
<select id="country" ng-model="country" ng-options="country for country in countries" class="ng-valid ng-dirty"><option value="" class="">Select</option><option value="0">usa</option><option value="1">canada</option><option value="2">mexico</option><option value="3">france</option></select>
</div>
<div>
City: <select id="city" ng-disabled="!cities" ng-model="city" class="ng-valid ng-dirty"><!-- ngRepeat: item in cities --><option value="" ng-repeat="item in cities" ng-disabled="item.disabled" class="ng-scope ng-binding">11111</option><option value="" ng-repeat="item in cities" ng-disabled="item.disabled" class="ng-scope ng-binding" disabled="disabled">22222</option><option value="" ng-repeat="item in cities" ng-disabled="item.disabled" class="ng-scope ng-binding" disabled="disabled">33333</option></select>
</div>
<div>
Suburb: <select id="suburb" ng-disabled="!suburbs" ng-model="suburb" ng-options="suburb for suburb in suburbs" class="ng-pristine ng-valid" disabled="disabled"><option value="" ng-disabled="item.disabled" class=""></option></select>
</div>
</div>
Reference

Categories

Resources