Dynamic dropdown select in AngularJS not working - angularjs

I am practicing with Angular and want to give users the option to choose from 3 dropdown select menus. The third menu should be dynamic depending on the selection from the previous two menus.
My html:
// First dropdown menu, static
<select ng-model="selectedLetter" ng-change="setColorSelection()"
ng-options="letter as letter for letter in letters">
</select>
<br>
// second dropdown menu, static
<select ng-model="selectedNumber" ng-change="setColorSelection()"
ng-options="number as number for number in numbers">
</select>
<br>
// third dropdown menu, should be dynamic
<select ng-model="selectedColor"
ng-options="color as color for color in colorSelection">
</select>
In my controller, I have the lists like this
$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];
var colors = {
'A1': [{"red": "100"}, {"pink": "101"}],
'A2': [{"blue": "202"}, {"black": "203"}],
'B1': [{"yellow": "304"}, {"orange": "305"}],
'B2': [{"white": "406"}, {"black": "407"}]
};
$scope.colorSelection = [];
$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelection = colors[$scope.selectedLetter + $scope.selectedNumber];
console.log($scope.colorSelection);
}
}
So if the user selects 'A' from the first menu and '2' from the second menu, he should see the options for 'A2' in the third menu.
Problem: currently, the third menu is not populating.
When I do console.log($scope.colorSelection), I get [Object, Object] in the console instead of [{"blue": "202"}, {"black": "203"}].
Also, I only want to display the colors in the menu, not the numbers associated with them. I was able to do this in ng-repeat using (key, value), not sure how I would do this in ng-options.

Change your color object like
var colors = {
'A1': [{"color": "Red", "code": "100"}, {"color":"pink", "code": "101"}]
};
and ng-option
<select ng-model="selectedColor"
ng-options="color.code as color.color for color in colorSelection">
</select>

Dropdown working properly and correctly. The problem in your json object [{"red": "100"}, {"pink": "101"}].
Dropdown can be used as the source object, or an array.
All possible options dropdown use, see the documentation.
I think there are two ways to change your json:
Transform it into an array of objects.
Transform it into a single object with the keys.
First way:
var colors = {
'A1': [{"color": "red", "code": "100"}, {"color":"pink", "code": "101"}]
};
Second way:
var colors = {
'A1': {"red": "100","pink": "101"}
};
See example on jsfiddle;
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];
var colorsByArray = {
'A1': [{
"color": "red",
"code": "100"
}, {
"color": "pink",
"code": "101"
}]
};
var colorsByObject = {
'A1': {
"red": "100",
"pink": "101"
}
};
$scope.colorSelection = [];
$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelectionByArray = colorsByArray[$scope.selectedLetter + $scope.selectedNumber];
$scope.colorSelectionByObject = colorsByObject[$scope.selectedLetter + $scope.selectedNumber];
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
Choose 'A'
<select ng-model="selectedLetter" ng-change="setColorSelection()" ng-options="letter as letter for letter in letters">
</select>
<br>Choose '1'
<select ng-model="selectedNumber" ng-change="setColorSelection()" ng-options="number as number for number in numbers">
</select>
<br>
<h3>
IterateByArray
</h3>
<select ng-model="selectedColor" ng-options="color.code as color.color for color in colorSelectionByArray">
</select>
<h3>
IterateByObject
</h3>
<select ng-model="selectedColor" ng-options="v as k for (k, v) in colorSelectionByObject">
</select>
</div>
</div>

Related

How to show default option in select option (drop down box) in an ng-repeat of rows?

I have a list of names and activities displayed with ng-repeat which shows tabular data (shortened for brevity). The list box populates and I can show which SchoolDayID was previously stored and the value for this updates if you change the selection in the drop-down. When the form loads it does not select any value in the drop-down list. For the ng-select I have tried several variations, none of which worked. I am several days into this and have no idea what I am doing wrong or failing to understand. How do I get each drop down per row to select the correct item?
I have tried:
<select ng-model="selectedSchoolDayID" ng-init="selectedSchoolDayID = a.SchoolDayID" ng-options="x.ID as x.code for x in AMListData" >
</select>
and even:
<select class="form-group">
<option id="selectedSchoolDay" name="selectedSchoolDay" value="{{AMListData[0].ID}}" selected="{{AMListData[0].ID}} == {{a.SchoolDayID}}">{{AMListData[0].code}}</option>
<option id="selectedSchoolDay" name="selectedSchoolDay" value="{{AMListData[1].ID}}" selected="{{AMListData[1].ID}} == {{a.SchoolDayID}}">{{AMListData[1].code}}</option>
<option id="selectedSchoolDay" name="selectedSchoolDay" value="{{AMListData[2].ID}}" selected="{{AMListData[2].ID}} == {{a.SchoolDayID}}">{{AMListData[2].code}}</option>
</select>
Data for list box:
$scope.AMListData = participationSvc.amlist();
// from participationSvc:
'amlist': function listSelectionsController($scope) {
return [
{ ID: '0', code: 'PM Programming' },
{ ID: '1', code: 'AM Programming' },
{ ID: '2', code: 'Supplemental' }
];
},
HTML/AngularJS part:
<div ng-repeat="a in selectedAttendees | orderBy : a.LastName">
<!-- there could be many rows, once per name of person. each row should have a drop-down of its own -->
<div class="row">
<div>{{a.LastName}}</div>
...
<select class="col-md-5" id="SchoolDay" name="SchoolDay" ng-model="a.SchoolDayID">
<option data-ng-repeat="x in AMListData" name="SchoolDay" value={{x.ID}} ng-selected="{{(x.ID == selectedSchoolDay) ? true: false}}" >{{x.code}}</option>
</select>
<!-- Show me current selection and drop-down list data -->
<b> Selected ID: {{a.SchoolDayID}}</b>
<br />
<ul>
<li ng-repeat="x in AMListData">{{x.ID}} {{x.code}}</li>
</ul>
</div>
</div>
You can use default value in controller
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedSchoolDayID" ng-options="x.ID as x.code for x in AMListData" >
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a={
//SchoolDayID:'2'
};
$scope.selectedSchoolDayID=$scope.a.SchoolDayID || '1';//'1' is Default Value
$scope.AMListData=[
{ ID: '0', code: 'PM Programming' },
{ ID: '1', code: 'AM Programming' },
{ ID: '2', code: 'Supplemental' }
];
});
</script>
</body>
</html>

how to show default dropdown value show top angularjs

I have a dropdown show below card information and i want to show is_default= true card show top other cards below.. please help me
<select ng-model="approvedinvoicesCtrl.currentcard.card_id">
<option ng-value="item.card_id" ng-repeat="item in approvedinvoicesCtrl.current_job.cards ">{{item.brand +' '+ item.last_digits}}</option>
</select>
{brand:"Visa",
card_id:"card_19VHhAGdj8iWoXDURuRqNH28",
last_digits : 123123,
is_default:true},
{
brand:"Master",
card_id:"card_19VHhAGdj8iWoXDURuRqNH28",
last_digits : 123123,
is_default:false}
Suggesting you with this
<select>
<option ng-value="item.card_id" ng-repeat="item in dropdownval "
ng-selected=item._default >
{{item.brand +' '+ item.last_digits}}</option>
</select>
LIVE DEMO
I will suggest to use ngOptions on option element instead of ng-repeat.
Note: ngOptions provides an facility for the "option" element which should be used instead of ngRepeat when you want the select model to be bound to a non-string value. This is because an option element can only be bound to string values at present. For more information you can check this link.
Working demo with ngOptions :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.current_job = {
"cards": [
{
brand:"Visa",
card_id:"card_19A",
last_digits : 123123,
is_default:true
}, {
brand:"Master",
card_id:"card_19B",
last_digits : 123123,
is_default:false
}
]
};
for (var i in $scope.current_job.cards) {
if ($scope.current_job.cards[i].is_default == true) {
$scope.topCard = $scope.current_job.cards[i].card_id;
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-options="item.card_id as item.brand+' '+item.last_digits for item in current_job.cards"
ng-model="topCard">
</select>
</div>
Working demo with ngRepeat :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.current_job = {
"cards": [
{
brand:"Visa",
card_id:"card_19A",
last_digits : 123123,
is_default:true
}, {
brand:"Master",
card_id:"card_19B",
last_digits : 123123,
is_default:false
}
]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-model="currentcard.card_id">
<option ng-value="item.card_id" ng-repeat="item in current_job.cards" ng-selected="item.is_default">{{item.brand +' '+ item.last_digits}}</option>
</select>
</div>
You should use the ng-init and the ng-options for defaults values like:
<select ng-init="somethingHere = options[1]"
ng-model="somethingHere"
ng-options="option for option in options">
</select>
$scope.options = [
'Brand1',
'Brand2',
'Brand3'
];
You can use orderby
<select ng-model="approvedinvoicesCtrl.currentcard.card_id><option ng-value="item.card_id" ng-repeat="item in approvedinvoicesCtrl.current_job.cards | orderBy:'is_default':false">{{item.brand +''+ item.last_digits}}</option></select>
Here item 'is_default' property is sorted in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.
#link http://docs.angularjs.org/api/ng.filter:orderBy
You may prefer pre-selecting the card (option selected) instead of sorting using the default card at the top.
You can use the ng-selected using the default value if no value is selected in ng-model , otherwise, it selects the value in ng-model.
<select ng-model="currentCard.selected" >
<option
ng-value="item.card_id" ng-repeat="item in cards"
ng-selected="(currentCard.selected==item.card_id) || (!currentCard.selected && item.is_default)">
{{item.brand +' '+ item.last_digits}}
</option>
</select>
or you can use the ng-options approach. In this last case, you can pre-select an option using the ng-model value only.
<select
ng-model="currentCard.selected"
ng-options="item.card_id as item.brand+' '+item.last_digits for item in cards">
</select>
See this fiddle with both examples:
https://jsfiddle.net/hdca55cg/
The second one shows default card if you have previously selected in the model.

AngularJS - Ng-change updating value but not toggling radio button

I have two input options that are linked via ng-model in order to display always the same country in both places.
<select ng-model="selectedCountry" ng-options="country.name for country in countries">
<select ng-model="selectedCountry" ng-options="country.name for country in countries">
Each country has different shipping costs, and once the country is selected you can also choose between different shipping options ("normal" and "express" with a radio button. I want to make it always display the "normal" cost when switching the country, and I made it by adding a ng-click to each of the input options and adding a ng-change in order to listen to the changes:
<select ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="changeShipping()" ng-click="shippingPrice=selectedCountry.shipping.normal">
The problem is that while the data shown in the view is the correct when changing the country, but the radio button is still set in the wrong option.
This is my controller logic:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.countries = [{
"name": "Freedonia",
"shipping" :
{
"normal":30,
"express":70
}
},{
"name": "Mordor",
"shipping" :
{
"normal":70,
"express":110
}
},{
"name": "Oz",
"shipping" :
{
"normal":140,
"express":180
}
}];
$scope.selectedCountry = $scope.countries[0];
$scope.changeShipping = function() {
return $scope.shippingPrice = $scope.selectedCountry.shipping.normal;
};
});
You can see a working fiddle here Thanks in advance!
Use ng-model with input[radio] and set it's value on select change.
UPDATED JSFIDDLE
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.shippingType = 'normal'; // initial value for input[radio]
$scope.countries = [{
"name": "Freedonia",
"shipping": {
"normal": 30,
"express": 70
}
}, {
"name": "Mordor",
"shipping": {
"normal": 70,
"express": 110
}
}, {
"name": "Oz",
"shipping": {
"normal": 140,
"express": 180
}
}];
$scope.selectedCountry = $scope.countries[0];
$scope.changeShipping = function () {
$scope.shippingType = 'normal'; // set back to normal on country change
return $scope.shippingPrice = $scope.selectedCountry.shipping.normal;
};
});
.summary{
background-color:gray;
border:1px solid black;
font-family:Arial;
margin-bottom:52px;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="myCtrl" ng-app="myApp">
<div class="summary">
Summary:<br>
Country:<select ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="changeShipping()">
</select><br>
Shipping Costs:
{{selectedCountry.shipping[shippingType]}}
</div>
<div>
<select ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="changeShipping()">
</select>
</div>
Shipping costs:
<form>
<input type="radio" name="shippingOptions" value="normal" ng-model="shippingType">
Normal {{selectedCountry.shipping.normal}}<br>
<input type="radio" name="shippingOptions" value="express" ng-model="shippingType">
Express {{selectedCountry.shipping.express}}<br>
</form>
</div>

AngularJS <select> view value not updated

I have an array of models. I start with one model, then copy that model and push it to the stack. My view shows the array of models in one page.
But the view for the copied models isn't correct. More specifically the <select> isn't displaying the correct value.
Controller:
$scope.colors = [
{
id: 1,
name: 'Green'
},
{
id: 2,
name: 'Red'
}
];
var itemModel = {
name: '',
color: null
};
$scope.items = [
angular.copy(itemModel)
];
$scope.copyItem = function(item) {
$scope.items.push(angular.copy(item));
};
Plunker: https://plnkr.co/edit/sVBL9j3JmCjdLZtr7HCH?p=preview
Any suggestions?
How about this:
<select ng-model="item.color" ng-options="color.name as color.name for color in colors">
<option value="">None</option>
</select>
Try this:
<select ng-model="item.color" ng-options="color as color.name for color in colors track by color.id">
<option value="">None</option>
</select>

Select options through ng-click is not working in chrome browser using AngularJS

I need to use ng-click so that I can pass three parameters and set in my local json based on the selection.
<select>
<option id="" value="">--Select--</option>
<option ng-repeat="comparison in comparisons" ng-click="setSkillComparisonOperator(index,comparison.sid,comparison.name)"
ng-selected="comparison.sid == data.value.comparisonOperator.sid">{{comparison.name}}</option>
</select>
I can use it ng-model and ng-change as follows.
<select ng-model="item" ng-options="o.id as o.id for o in list" ng-change="onFunction(item)">{{item}}</select>
In that case , I can't pass three parameters as follows.
<select ng-model="item" ng-options="o.id as o.id for o in list" ng-change="onFunction(o.id,o.name)">{{item}}</select>
At last , I found solution.
JS fiddle link
HTML page is
<div ng-app="miniapp">
<div ng-controller="Ctrl">
<select ng-model="selectedColor" ng-options="color as color.name for color in colors" ng-init="selectedColor = check(color1,colors)" ng-change="setColor(selectedColor)">
<option value="">Select A Color</option>
</select>
<br/>
<br/>
Color Id: <span ng-bind="colorId"></span>
<br/>
Color name: <span ng-bind="color"></span>
<br/>
Color shade: <span ng-bind="shade"></span>
<br/>
</div>
</div>
Javascript is
var $scope;
var app = angular.module('miniapp', []);
function Ctrl($scope) {
$scope.colorId = 4;
$scope.shade = null;
$scope.color = null;
$scope.color1 = {name:'Red', value: 'red',id:2};
$scope.colors = [
{name:'Red', shade: 'white',id:1},
{name:'Orange', shade: 'red',id:2},
{name:'Yellow', shade: 'blue',id:3},
{name:'Green', shade: 'yellow',id:4},
{name:'Blue', shade: 'indigo',id:5},
{name:'Indigo', shade: 'violet',id:6},
{name:'Violet', shade: 'orange',id:7}
];
$scope.check =function(selectedColor,colors){
var i = null;
for(i in colors){
if(colors[i].id == selectedColor.id){
return colors[i];
}
}
};
$scope.setColor= function(color){
$scope.colorId = color.id;
$scope.shade = color.shade;
$scope.color = color.name;
};
};
Angular actually takes care of this form you with ng:model. You don't need to pass any parameters.
In your callback function you can do this:
$scope.onFunction = function() {
var id = $scope.item.id;
var name = $scope.item.name;
...
};
I have the same problem and I solve this as Krish Lakshmanan did. I also added:
<option value="">Some text</option>
OR (force to select a member from the list)
$scope.options = [1,2,3];
$scope.d = $scope.options[0];
I don't know why but using Chrome with AngularJs, this bug of selection happens, I think problem is at Chrome, because Firefox it worked (I thought firefox sets the value on focus out the input).
I found this thread here:
https://github.com/angular/angular.js/issues/4836
The bug: http://jsbin.com/wofejo/1/
The workaround here: http://jsfiddle.net/JqnMr/
The workaround 2 here: http://jsfiddle.net/y61pacre/
And this issue on chromium: https://code.google.com/p/chromium/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Pri%20M%20Week%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified&groupby=&sort=&id=415505
I hope I helped someone, if you find the solution without using an empty option or forcing the selection of a member, please tell me! :)

Resources