How to get ID from Angular dropdown from value? - javascript

As you can see in the code, I have a list cars Car A,B, and C with corresponding ids in availableCars list. I’m getting already chosen car from a service. It is not an object just the car name. User has option to choose different car but on change, I have to send car id to other service. Is there any simplest way to achieve my goal?
(function(angular) {
'use strict';
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.carName = (function getCarNameFromService(){
return 'Car B';
})();
$scope.availableCars = [
{id: '1A', name: 'Car A'},
{id: '2B', name: 'Car B'},
{id: '3C', name: 'Car C'}
]
}]);
})(window.angular);
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ngrepeat-select-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="ngrepeatSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="carName">
<option ng-repeat="option in availableCars" value="{{option.name}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>selected car name = {{carName}}</tt><br/>
<tt>selected car id = ???</tt><br/>
</div>
</body>
</html>

Rather than using an ng-repeat on the "option" element inside of a select, you can use "ng-options". ng-options
I created a plnkr to illustrate your example. Some of the key pieces of code are as follows:
JS
var carName = "Car B"; //name provided to this controller
$scope.availableCars = [
{id: '1A', name: 'Car A'},
{id: '2B', name: 'Car B'},
{id: '3C', name: 'Car C'}
]
$scope.selectedCar = $scope.availableCars.filter(function(car){
return car.name === carName;
})[0];
$scope.selectedId = $scope.selectedCar.id;
$scope.updateCar = function(id){
$scope.selectedId = id;
}
and
HTML
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select ng-options="car as car.name for car in availableCars" ng-model="selectedCar" ng-change="updateCar(selectedCar.id)"></select>
</form>
Notice the "ng-change" and the "ng-options" in the html.

User has option to choose different car but on change, I have to send car id to other service
You could use ng-change for that:
<select ng-change="sendInfo(...)" ...>
...
</select>
Actually, I would advise to bind to the model the car id instead of the car name. Or a car object, providing you switch to ng-options. That way you could send the selected id.

Related

setting selected value as undefined in angualrjs

I am using angularjs ng-options and ng-model directives in my view to set the select option and get notified when dropdown option is selected or changed. I am also adding extra empty option so that user can deselect this and for that I want value in ng-model expression to be undefined. Is there any way to do that ? I tried adding value=="{{undefined}}" but that takes out the empty option totally.
Here is the plunker example where if I select the empty option then data.model should be undefined but here it is coming as null.
https://plnkr.co/edit/d9Jzs4YgqpWHbOxonwa3?p=preview
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-select-ngvalue-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="ngvalueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="ngvalueselect"> ngvalue select: </label>
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option label='' value="{{undefined}}"/>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
</form>
<hr>
<pre>model = {{data.model === undefined | json}}</pre><br/>
</div>
</body>
</html>
Corresponding app.js is
(function(angular) {
'use strict';
angular.module('ngvalueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{value: 'myString', name: 'string'},
{value: 1, name: 'integer'},
{value: true, name: 'boolean'},
{value: null, name: 'null'},
{value: {prop: 'value'}, name: 'object'},
{value: ['a'], name: 'array'}
]
};
}]);
})(window.angular);
Thanks
There are two issues with your code:
Your dropdown allows multiple select thanks to the multiple attribute. This means that your model stores array of selections. The value you are looking for is one of the elements of the array, but in your code you are comparing undefined to the whole array.
Your additional option should use ng-value instead of value attribute. You don't need to write is as separate option, you can add it to availableOptions object (as {value: undefined, name: ''}).
Here is the updated plunker:
https://plnkr.co/edit/RXUlW6P7DX2wPZOazwe8?p=preview

Handling dropdown in angular js

I have a dropdown with some values :
Apple
Mango
Orange
Grapes
HTML :
<div class="form-group">
<label class="control-label col-sm-20" for="groupz">Role*</label>
<select class="form-control" ng-model="model.selectedRole" name="role" ng-change="GetRole(model.selectedRole)" >
<option value class selected>Select Roles</option>
<option ng-repeat="item in model.roles track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
I want my $scope.selectedRole to be by default as Apple. But later when the user needs to change the value, they can change it from apple to orange or any other fruit name. I have separate service request to fetch the fruits from backend and I write my code in controller as follows.
$scope.GetRole = function() {
$scope.selectedrole = [];
if ($scope.model.selectedRole != null) {
for (var i = 0; i < 1; i++) {
$scope.selectedrole.push($scope.model.selectedRole);
}
}
}
I hope this helps you
JsFiddle
In js
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.selectedrole = ['Apple', 'Mango', 'Orange', 'Grapes'];
$scope.selectRole= $scope.selectedrole[0];
});
In HTML
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectRole" ng-options="role for role in selectedrole">
</select>
</div>
just try : HTML
<select class="form-control select" name="role" id="role" data-ng-model="ctrl.model.selectedRole" data-ng-options="option.name for option in ctrl.model.roles track by option.id"></select>
in your contoller
$scope.model = {
roles: [{
id: '1',
name: 'Apple'
}, {
id: '2',
name: 'Orange'
}, {
id: '3',
name: 'Mango'
}],
selectedRole: {
id: '1',
name: 'Apple'
} //This sets the default value of the select in the ui
};
Then assign the first array element to selectedrole containing the array of values(Apple Mango Orange Grapes).
If you want the default to be apple and the array is ordered:
array = [Apple, Mango, Orange, Grapes]
Your model needs to be set to selectedRole:
data-ng-model="selectedRole"
In your controller, set:
selectedRole = array[0]
angular will take care of the rest of the data manipulation.
I hope this helps. Please provide more information for a clearer answer
Thanks
Handling a select element i.e. a drop down list in AngularJS is pretty simple.
Things you need to know is that you bind it to an array or a collection to generate the set of option tags using the ng-options or the ng-repeat directives which is bound to the data source on your $scope and you have a selected option which you need to retrieve as it is the one the user selects, it can be done using the ng-model directive.
If you want to set the selected option on the page load event, then you have to set the appropriate object or value (here it is the fruit id) which you are retrieving from data binding using the as clause in the ng-options directive as shown in the below embedded code snippet
ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
or set it to the value of the value attribute when using the ng-repeat directive on the option tag i.e. set data.model to the appropriate option.value
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
angular
.module('fruits', [])
.controller('FruitController', FruitController);
function FruitController() {
var vm = this;
var fruitInfo = getFruits();
vm.fruits = fruitInfo.fruits;
vm.selectedFruitId = fruitInfo.selectedFruitId;
vm.onFruitChanged = onFruitChanged;
function getFruits() {
// get fruits and selectedFruitId from api here
var fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Mango' },
{ id: 3, name: 'Banana' },
{ id: 4, name: 'Orange' }
];
var fruitInfo = {
fruits: fruits,
selectedFruitId: 1
};
return fruitInfo;
}
function onFruitChanged(fruitId) {
// do something when fruit changes
console.log(fruitId);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fruits">
<div ng-controller="FruitController as ctrl">
<select ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
ng-model="ctrl.selectedFruitId"
ng-change="ctrl.onFruitChanged(ctrl.selectedFruitId)">
<option value="">Select Fruit</option>
</select>
</div>
</div>
Check the Example section here for more information.

Angular: How to use ng-options to make four separate selections?

JS:
angular
.module('app', [])
function MainCtrl() {
var ctrl = this;
ctrl.selectionList = [
{ id: 1, name: 'apple'},
{ id: 2, name: 'banana'},
{ id: 3, name: 'grapes'},
{ id: 4, name: 'carrot'}
];
ctrl.selectedThing = ctrl.selectionList[0].name;
}
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
HTML:
<div class="row">
<div class="col-sm-3 col-xs-12 unit">
<select
ng-model="ctrl.selectedThing"
ng-options="selections.name as selections.name for selections in ctrl.selectionList">
</select>
</div>
</div><!--end of first row-->
So this code creates four different selections.
The problem is that when I choose an option, let's say for example "apples" on one selection, all the other selections become apples too. Is there any way to solve this with ng-options or should I just write the select in HTML?
You definitely want to use ng-options, as that isn't the issue here. The problem you are seeing is most likely because the ng-model on all of your select elements is the same ctrl variable. So when you update one of them, it changes a single variable that is bound to all four dropdowns. You either need to setup up an array for your selected items, or four different instances of a selected variable.
ctrl.selectedThings = [ctrl.selectedList[0].name, '', '', ''];
Then in your view you can do this...
<select
ng-model="ctrl.selectedThings[rowIndex]"
ng-options="selections.name as selections.name for selections in ctrl.selectionList">
</select>
Not the most robust solution if you are going past 4 items, but you should be able to adapt it to be dynamic.
Your code is working fine, can you check and confirm?!
(function ()
{
var app = angular.module("app", []);
function HomeController()
{
var vm = this;
vm.selectionList = [
{ id: 1, name: 'apple'},
{ id: 2, name: 'banana'},
{ id: 3, name: 'grapes'},
{ id: 4, name: 'carrot'}
];
}
app.controller("HomeController", [HomeController]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Angular JS App</title>
</head>
<body>
<div class="container" ng-controller="HomeController as homeCtrl">
<div class="row">
<div class="col-sm-3 col-xs-12 unit">
<select
ng-model="homeCtrl.selectedThing"
ng-options="selections.name as selections.name for selections in homeCtrl.selectionList">
</select>
<pre>{{homeCtrl.selectedThing}}</pre>
</div>
</div><!--end of first row-->
</div>
</body>
</html>
If you have ng-model="ctrl.selectedThing" for all of your <select> tags, they will all change to the same selection because they're using the same scope property. Think of it like having 4 variables referencing the same data: if you change one, access any of the variables will retrieve the same result.
You need to bind all of your selects to a different property on scope, so ctrl.selectedThing1,2,...n. That's not very scalable, but that would fix your problem.

How to display the selected value in select option field from the json object fetched form server angularjs

I have fetched a json object with the list of countries. And now i want to display the selected name of the country in the select option box. I've tried different ways but there always keep showing the blank value.
Note:countries is the json object having the list of countries with key value pair. It used to display the select option in the view. And tabs[0].data.country is the value of country id which is to be selected.
Some of the codes i have tried:
Code to display the selected country name:
Code to display the select option in View:
Output:
Convert you json object into an array of objects first, and then you do something like
<select name="countries" id="contries" ng-model="vm.country">
<option ng-repeat="country in vm.countries" value="{{country.id}}">{{country.name}}</option>
</select>
Just loop over them and pick what you want from the list. Full documentation here: https://docs.angularjs.org/api/ng/directive/select
Well finally, here is the snippet that solved my problem.
html
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption">
</select>
</form>
</div>
js
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
};
}]);
For more information you can go to this link
Also another useful tutorial here

How to populate the list of all countries into select multiple and then determine which ones were selected

In my Angular app I have a task of presenting to the user a "select multiple" list of ALL countries, and, after they make their multiple selections, to be able to determine which countries were selected.
I understand how to use ng-repeat inside of the tag, but, I don't know how to properly populate my $scope.countries model array in my controller. ( my only guess is to have the entire country list in a database, and then use ng-init to push all records onto the $scope.countries array, but I'm not sure if this is the best way to do this)
My second challenge is to be able to iterate over the select object, after one or more items were selected, and determine which once were selected.
Currently, my select looks like this:
<div class="form-group">
<label for="selectbasic">What country is the data for</label>
<div>
<select type="text" class="form-control multiselect multiselect-icon" multiple="multiple" ng-model="SelectedCountries">
<option ng-repeat="country in countries">
{{country.name}}
</option>
</select>
</div>
</div>
And my controller looks like this:
$scope.countries = [
{
name: "US"
},
{
name: "UK"
},
{
name: "France"
}
];
Try this: http://jsfiddle.net/tarris/6S2Nk/
Here's the gist of it:
<div ng-app="myApp">
<div ng-app="myApp" ng-controller="con">
<div ng-repeat="item in countries">
<input type='checkbox' ng-model="item.checked" />{{item.name}}
</div>
<button ng-click="checkit()">Check it</button>
</div>
</div>
and the javascript:
var myApp = angular.module('myApp', []);
myApp.controller('con', ['$scope', function($scope){
$scope.countries = [
{id:'us', name: 'United States', checked: false},
{id:'fr', name: 'France', checked: false},
{id:'sw', name: 'Sweden', checked: true}
];
$scope.checkit = function(){
var list = [];
for(var p in $scope.countries){
if($scope.countries[p].checked){
list.push($scope.countries[p].name);
}
}
alert(list);
};
}]);

Categories

Resources