In my project, i need to select multiple options from a drop down. My code looks something like this:
//Controller
$scope.data = [{id: 1, Country: Zambia},
{id: 2, Country: United Kingdom}
{id: 3, Country: USA}]
$scope.selectedCountry = [];
//view
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple
ng-options="country.country as country.country for country in data"></select>
<h4> {{selectedCountry}}</h4>
The context above works and i can select multiple options from the dropdown. This link helped me to achieve this.
The problem.
Now the problem i'm having is that when i select the options from the dropdown i need to be able to pass the id and country in the selectedCountry array and not just the country. so for instance in the above context when you select the first country , the information passed through the to the selectedCountry Array will be something like this ["zambia"] but really what i'm looking for is something like this
[{id: 1, Country Zambia}].
To solve this problem i attempted to do this in the view:
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple
ng-options="{Id: country.Id, Country: country.country } as country.country for country in data"></select>
<h4> {{selectedCountry}}</h4>
That worked well and the data passed to the selectedCountry array is an object like {id: 1, Country: zambia} but the issue is that i cannot select multiple options from the dropdown i can only select 1 option.
What am i doing wrong? and what is the best way to achieve this?
Thank you
I've found some mistakes in your code:
Your JSON data is invalid. JSON string values must be in double
quote, the same for keys {"key":"value"}. Every item in an array
must be splitted by commas.
The correct key for the country name is "Country".
I'm using Angular 1.4.8.
You can use a shorter version of your code by using: country.Country for country in data
Something like this:
(function() {
var app = angular.module("app", []);
app.controller("controller", ["$scope",
function($scope) {
$scope.selectedCountry = [];
$scope.data = [{
"id": 1,
"Country": "Zambia"
}, {
"id": 2,
"Country": "United Kingdom"
}, {
"id": 3,
"Country": "USA"
}];
}
]);
})();
div {
margin: 2px;
}
.largeversion {
border: solid 1px #FF0000;
}
.shortversion {
border: solid 1px #005500;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div data-ng-app="app">
<div data-ng-controller="controller">
<div class="largeversion">
<pre>ng-options="{Id: country.Id, Country: country.Country } as country.Country for country in data"</pre>
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple ng-options="{Id: country.Id, Country: country.Country } as country.Country for country in data"></select>
</div>
<div class="shortversion">
<pre>ng-options="country.Country for country in data"</pre>
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple ng-options="country.Country for country in data"></select>
</div>
<h4> {{selectedCountry}}</h4>
</div>
</div>
Related
I am trying to make dependent dropdown using JSON data
Used (for in) to get the key to integrate it in the dropdown but didn't work,whatever i searched every time json data is getting accessed by key to get the value in this structure i am able to get it in dropdown [{name:"india"},{name:"usa"}].But with current json structure i am not able to do it.
HTML:-
<div ng-controller="myCtrl3">
<select>
<option>Select Country</option>
<option ng-repeat="country in chooseCountries"></option>
<option ng-repeat="states in country"></option>
<option ng-repeat="city in states"></option>
</select>
</div>
JS:-
app.controller('myCtrl3',function($scope,$http){
$http({
url:'js/country.json',
method:'GET'
})
.then(function(response){
$scope.chooseCountries = response.data;
});
});
JSON(country.json):-
[{
"INDIA": {
"KARNATAKA": ["BANGALORE", "UDUPI", "MANGALORE"],
"TELENGANA": ["HYDERABAD", "GUNTUR", "SHANKERPALLY"]
},
"USA": {
"CALIFORNIA": ["SAN JOSE", "SAN HOSE", "NEW YORK"],
"FLORIDA": ["MIAMI", "DENVER"],
"INDIAPOLIS": ["INDIANA", "MASACHUTTEUS"]
},
"AUSTRALIA": {
"NEW SOUTH WALES": ["SYDNEY", "BRISBANE"],
"QUEENSLAND": ["PERTH", "VICTORIA"],
"WESTERN AUSTRALIA": ["MELBOURNE", "MCG"]
}
}]
i want the output first dropdown should show INDIA,USA,AUSTRALIA if i click INDIA second dropdown should show KARNATAKA AND TELENGANA in the third dropdown list if i click KARNATAKA it should show BANGALORE,UDUPI,MANGALORE.Didn't got any error but coudn't get the desired output.
I'm guessing you can't alter the format of the returned JSON. If that is the case, you don't have a nicely formed object hierarchy that you can use so instead you'll have to fall back to using (key, value). Below is a simple example of how you can accomplish what you are after.
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.countryChoices = [{
"INDIA": {
"KARNATAKA": ["BANGALORE", "UDUPI", "MANGALORE"],
"TELENGANA": ["HYDERABAD", "GUNTUR", "SHANKERPALLY"]
},
"USA": {
"CALIFORNIA": ["SAN JOSE", "SAN HOSE", "NEW YORK"],
"FLORIDA": ["MIAMI", "DENVER"],
"INDIAPOLIS": ["INDIANA", "MASACHUTTEUS"]
},
"AUSTRALIA": {
"NEW SOUTH WALES": ["SYDNEY", "BRISBANE"],
"QUEENSLAND": ["PERTH", "VICTORIA"],
"WESTERN AUSTRALIA": ["MELBOURNE", "MCG"]
}
}];
$scope.selectedCountry = {};
$scope.selectedState = {};
$scope.selectedCity = '';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div>
<select ng-model="selectedCountry" ng-options="value as key for (key, value) in countryChoices[0]"></select>
</div>
<div>
<select ng-model="selectedState" ng-options="value as key for (key,value) in selectedCountry"></select>
</div>
<div>
<select ng-model="selectedCity" ng-options="value as value for value in selectedState"></select>
</div>
</div>
In order for that to work, your json data should be like this:
[{
country: "INDIA",
states: [
{
"KARNATAKA": {
cities: ["BANGALORE", "UDUPI", "MANGALORE"]
}
}
}]
Hope it helps...
Once I use ng-options for a select I am unable to get dafault selection to work on nested json objects.
once I have a bit more complicated json and the select should handle a child object my select does not default select the proper value.
Given test = {"id":3,"title":"Test","product":{"id":4,"name":"Test1"}} as my ng-model test.product and
[{
"id": 4,
"name": "Test1"
}, {
"id": 5,
"name": "Test2"
}]
as my selection option. (see http://embed.plnkr.co/mpnislw77UBSEdHl4UKN/)
I seem to be unable to figure out how to facilitate default selection.
If you use track by item.id it works - http://embed.plnkr.co/mpnislw77UBSEdHl4UKN. The marked answer was not very obious since the ng-model is nested in iself. but it contains the correct information.
The only problem with your code is that you've assigned a new object to $scope.test.product and you're using it as the ng-model of the dropdown.
This makes AngularJS unable to find it inside the possible values, which are $scope.testarray. AngularJS will compare two objects by their reference, which you broke when you assigned a new object to $scope.test.product.
To make it working, change $scope.test as follows:
$scope.test = {
"id": 3,
"title": "Test",
"product": $scope.testarray[1]
}
This is how to select with ngOptions and setting a default value
Example
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
};
}]);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="defaultValueSelect">
<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>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
</body>
</html>
try this, hope it will help
<option value="" ng-if="false"></option>
I'm a pretty new in this area (one mounth) and I'm developing application with angularJs, I'm getting back Json requisition with a list, I have to put the name ({{empresa.name }}) when the user select I get the ID({{empresa.IdEmpresa}}).
I want use ng-repeat for that, something like (ng-repeat="empresa in empresas").
I'm getting the Json with the list from the JavaController, my Entity is named Empresa, I declare a empty object on angular Like that ( $scope.empresas = {}) and give the callback to this emprty object, right?!
My select field is like that
<label>Empresa</label>
<select class="form-control">
<option value="{{empresa.EmpresaId}}">{{empresa.name}}</option>
</select>
how do I use repeat in this ?
Assuming your JSON data look like this
$scope.empresas = [
{ EmpresaId: 1, name: 'one' },
{ EmpresaId: 2, name: 'two' },
{ EmpresaId: 3, name: 'three' }
]
Apart from using ng-repeat on <options>, you can also utilise ng-options
<select ng-options="e.EmpresaId as e.name for e in empresas" ng-model="???"></select>
You can use ng-repeat="empresa in empresas" on the <option> tags.
Here's an example:
<select>
<option ng-repeat="empresa in empresas" value="{{empresa.EmpresaId}}">{{empresa.name}}</option>
</select>
Controller Code
$scope.empresas = [
{ EmpresaId: 101, name: 'India' },
{ EmpresaId: 102, name: 'US' },
{ EmpresaId: 103, name: 'UK' }
];
I have following data for drop down in my controller.
$scope.groups={{"gpId": 3, "name" :"Tom"}, {"gpId": 32, "name" :"Helen"},{"gpId": 9, "name" :"Amy"}
$scope.user=
{
tkId: 32;
place: NW
}
In my html I have following select
<select ng-model="user.tkId" ng-options="a.gpId as a.name for a in groups track by a.gpId></select>
When I run this I get drop down with Helen selected but when i want to change the selection from drop down it doesn't let me.
Please let me know how I can change it to select other options so I can save it if needed. Thanks
The following snippet works.
First, an array of objects is written like this [{}, {}]
It's written in the angular docs that track by and as should not be used together.
Don't use select as and track by in the same expression. They're not designed to work together.
<body ng-app="selectExample">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.groups = [{
"gpId": 3,
"name": "Tom"
}, {
"gpId": 32,
"name": "Helen"
}, {
"gpId": 9,
"name": "Amy"
}];
$scope.user = {
tkId: 32,
place: 'NW'
};
}]);
</script>
<div ng-controller="ExampleController">
<label>Group:
<select ng-model="user.tkId" ng-options="group.gpId as group.name for group in groups"></select>
</label>
<br/> {{user.tkId}}
</div>
</body>
I have created an AngularJS application with select box, The application with select is working fine, but the problem is that I want option group like thing in select which is selectable, since i am aware that the option group feature in select is not selectable, I made similar stuff using CSS, when i put the values statically its working fine, but dynamically I am not able to show the child details
JSFIDDLE
can anyone please tell me some solution for this
angular.module('Test1',[])
.controller('Foo', function($scope) {
$scope.regionsData = {
"regions": [
{
"regionId": 15,
"regionName": "Kerala",
"places": [
{
"placeId": 21,
"placeName": "Trivandrum"
},
{
"placeId": 22,
"placeName": "Kollam"
}]
},
{
"regionId": 16,
"regionName": "Chennai",
"places": [
{
"placeId": 23,
"placeName": "Kanchipuram"
},
{
"placeId": 24,
"placeName": "Guindy"
}]
}
]
}
});
.region {
font-weight: bold
}
.place {
padding-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Test1">
<div ng-controller="Foo">
<b>DYNAMIC<b><br>
HOW CAN I DISPLAY THE CHILD DETAILS<br>
<select ng-model="data.selectedDocumentType" class="region" ng-options="region as region.regionName for region in regionsData.regions"> </select>
<br><br><b>STATIC<b><br>
THIS IS WHAT I WANT TO ACHIEVE<br>
<select>
<option class="region">Kerala</option>
<option class="place">Trivandrum</option>
<option class="place">Kollam</option>
<option class="region">Chennai</option>
<option class="place">Kanchipuram</option>
<option class="place">Guindy</option>
</select>
</div>
</div>
FYI, google chrome doesn't allow adding css to option elements, see this
answer
I found this to work:
example
as mentioned in the comments, I re formatted the data in a simpler fashion, using loops on the original variable:
$scope.test = [];
$scope.regionsData.regions.forEach(function(val, key) {
$scope.test.push(val.regionName);
val.places.forEach(function(val, key){
$scope.test.push(val.placeName);
})
})
and in html:
<select ng-model="data.selectedDocumentType" class="region" ng-options="region for region in test"> </select>
to overcome chrome's issue, and apply css, a better approach is to use <ul> with <li> to make the dropdown.
here's an example of how to create the html, making in look like a dropdown is out of the scope of your question:
turn select into unordered-list fiddle
see this question on how to turn a ul into a dropdown