Angular JS ng-options selecting list from JSON - angularjs

I'm tryin to use a select with ng-options to populate my dropdown. This is my JSON
{
"Food": [
{
"Name": Apple,
"HealthCondition": [
{
"Name": "High Blood Pressure",
"Eat": null
},
{
"Name": "High Cholesterol",
"Eat": null
},
{
"Name": "Heart Disease",
"Eat": null
},
{
"Name": "Osteoporosis",
"Eat": null
},
{
"Name": "Digestive Disorder",
"Eat": null
}
]
}
And this is my select <select class="chosen-select" ng-model="selectedValue" ng-options="x.HealthCondition for x in myResults.Food" multiple chosen></select> and the result I'm getting is [object Object],[object Object],[object Object],[object Object],[object Object]
I'm trying to get a list of the Health Condition Names! Any help would be greatly appreciated. Stumped on this for hours. I'm using the Angular Chosen directive. This is working correctly if I just use the Name field like x.Name but I want to get HealthCondition Name.
Any help would be greatly appreciated!

Some Observations :
Your JSON is not valid. Apple should be a string against the name key.
You are iterating the Food array in ng-options it should be HealthCondition.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.jsonObj = {
"Food": [
{
"Name": "Apple",
"HealthCondition": [
{
"Name": "High Blood Pressure",
"Eat": null
},
{
"Name": "High Cholesterol",
"Eat": null
},
{
"Name": "Heart Disease",
"Eat": null
},
{
"Name": "Osteoporosis",
"Eat": null
},
{
"Name": "Digestive Disorder",
"Eat": null
}
]
}]};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select class="chosen-select" ng-model="selectedValue" ng-options="x.Name as x.Name for x in jsonObj.Food[0].HealthCondition" multiple chosen></select>
</div>

Try <select class="chosen-select" ng-model="selectedValue" ng-options="x.Name as x.Name for x in myResults.Food.HealthCondition" multiple chosen></select>

The issue is that your data is not able to be used for ng-options in its current format. You need to reduce the available HealthConditions down into a single array instead of multiple objects with a HealthCondition array as a property.
In your controller you will need to map the data to a single array like so:
$scope.HealthConditions = myResults.reduce(function(arr, result){
for(var i in result.HealthCondition){
arr.push(result.HealthCondition[i]);
}
return arr;
}, []);
And then in your view use the following:
<select class="chosen-select" ng-model="selectedValue" ng-options="x.Name for x in HealthConditions" multiple chosen></select>

Related

How to populate select ng-options with JSON object that has an string array?

currently I have this JSON object:
{
"hospitalId" : "0002",
"name" : "test form",
"procedureId" : "0002-testform",
"steps" : [
{
"title" : "Brand",
"value" : [
"jonson",
"smith",
"braun"
]
},
{
"title" : "Procedure type",
"value" : [
"total",
"unicompartimental"
]
}
]
}
And I need to display it on a multiselect, like this:
<strong>Brand</strong>
<ul>braun</ul>
<ul>jonson</ul>
<ul>smith</ul>
<strong>Procedure type</strong>
<ul>total</ul>
<ul>unicompartimental</ul>
They need to be ordered by steps.title and by steps.value, the thing is: I can't figure out how to display them correctly with a <select ng-options> tag, this is what I've tried:
<select multiple ng-model="step" ng-options="step[0].value group by step.title for step in loadedSteps.steps " ></select>
Gives me: Brand undefined
<select multiple ng-model="step" ng-options="step.value group by step.title for step in loadedSteps.steps | orderBy:['value']"></select>
Gives me: Brand [jonson, smith, braun]
Also I've tried with a nested <option> but it doesn't have ordering...
Any help would be very appreciated, thanks in advance
Here is the answer you are looking for.
You should use two ng-repeat, first for displaying title and other for displaying values inside the title.
The first ng-repeat starts with the title and ends with the values in that title.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names =
{
"hospitalId": "0002",
"name": "test form",
"procedureId": "0002-testform",
"steps": [{
"title": "Brand",
"value": [
"jonson",
"smith",
"braun"
]
}, {
"title": "Procedure type",
"value": [
"total",
"unicompartimental"
]
}]
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div >
<label>{{step.title}}</label>
<select>
<option ng-repeat-start="step in names.steps | orderBy:'title'" ng-bind="step.title"></option>
<option ng-repeat-end ng-repeat="opt in step.value | orderBy:'step.value':true" ng-bind="' - ' + opt"></option>
</select>
</div>
</div>
</body>
</html>
Please run this snippet
HEre is a plunker

Json Object in ng-repeat

response object like
$scope.list= [
Object {
cid=74,
date="2016-08-25T00:00:00.000+0530",
optkey="key",
optvalue="{
value:{
'name':test,
'gender':male
}
}"
},
Object {
cid=75,
date="2016-08-25T00:00:00.000+0530",
optkey="key",
optvalue="{
value:{
'name':test2,
'gender':female
}
}"
}},
Object {
cid=77,
date="2016-08-26T00:00:00.000+0530",
optkey="key",
optvalue="{
value:{
'name':test1,
'gender':female
}
}"
}]
and in html page used ng-repeat
<div ng-repeat="item in list">
{{item.date}} -- works fine
</div>
here how to display json value in object optvalue, done some code like.
<div ng-repeat="item in list">
{{item.optvalue.value}} -- but it is undefined
</div>
but it is not working can any one give hint for this
Just because your optvalue is a String but not a object. It should be :
optvalue = {
value:{
'name':test1,
'gender':female
}
}
In JSON, an object should NOT be in the parenthese.
Try this working example, please check the object created.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.list=
[
{
cid:74, date:"2016-08-25T00:00:00.000+0530", optkey:"key", optvalue:{value:{'name':'test','gender':'male'}}
},
{
cid:75, date:"2016-08-25T00:00:00.000+0530", optkey:"key", optvalue:{value:{'name':'test','gender':'male'}}
},
{
cid:76, date:"2016-08-25T00:00:00.000+0530", optkey:"key", optvalue:{value:{'name':'test','gender':'male'}}
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="item in list">
{{item.optvalue.value.name}}
</div>
</div>
The response JSON is not valid :
Strings should be wrapped in double quotes.
Expecting colon, not = in key value pairs.
Invalid characters found.
Invalid number.
Issue Capture :
Valid JSON :
[
{
"cid": 74,
"date": "2016-08-25T00:00:00.000+0530",
"optkey": "key",
"optvalue": {
"value": {
"name": "test",
"gender": "male"
}
}
},
{
"cid": 75,
"date": "2016-08-25T00:00:00.000+0530",
"optkey": "key",
"optvalue": {
"value": {
"name": "test2",
"gender": "female"
}
}
},
{
"cid": 77,
"date": "2016-08-26T00:00:00.000+0530",
"optkey": "key",
"optvalue": {
"value": {
"name": "test1",
"gender": "female"
}
}
}
]
In your case {{item.optvalue.value}} is giving undefined because optvalue is a string not an object.So, it should be an object.
"optvalue": {
"value": {
"name": "test1",
"gender": "female"
}
}
thanks for your answers,i have resolved it using--
angular.toJson and angular.fromJson
while send to server used
angular.toJson(stringOfJson)
and when got the response object the using
angular.fromJson(value)
and set to object field,it is working fine.
you need to change your code to this
<div ng-repeat="item in list">
{{item.optvalue.value.name}}
</div>

Grouping objects with AngularJS

I have a bunch of objects in an array and I am trying to figure out how to group them within an Angular repeater. For example I want to group the fruit items with a parentTag key to the Tag key of a parent. So Fruit has a tag of 1 and Apple has a parent tag with a value of 1, meaning Apple is grouped with Fruit.
so using this array...
[
{
"code":"Fruit",
"tag":1
},
{
"code":"Apple",
"tag":2,
"parentTag":1
},
{
"code":"Vegetable",
"tag":3
},
{
"code":"Meat",
"tag":4
},
{
"code":"Banana",
"tag":5,
"parentTag":1
},
{
"code":"Carrot",
"tag":6,
"parentTag":3
},
{
"code":"Chicken",
"tag":7,
"parentTag":4
}
]
I am trying to group the objects like this...
Fruit
Apple
Banana
Vegetable
Carrot
Meat
Chicken
So far I have a repeater that only displays the objects...
<div ng-repeat="product in products">
{{code}}
<span ng-if="product.tag != null">{{product.tag}}</span>
<span ng-if="product.parentTag > null">{{product.parentTag}}</span>
</div>
But I don't know how to use the groupBy in this case. any ideas?
Please see demo below
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
$scope.products = [{
"code": "Fruit",
"tag": 1
}, {
"code": "Apple",
"tag": 2,
"parentTag": 1
}, {
"code": "Vegetable",
"tag": 3
}, {
"code": "Meat",
"tag": 4
}, {
"code": "Banana",
"tag": 5,
"parentTag": 1
}, {
"code": "Carrot",
"tag": 6,
"parentTag": 3
}, {
"code": "Chicken",
"tag": 7,
"parentTag": 4
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="app">
<div ng-controller="homeCtrl">
<div ng-repeat="product in products | filter :{parentTag:'!'}">
<h3>{{product.code}}</h3>
<div ng-repeat="subproduct in products | filter :{parentTag:product.tag}">
<span>{{subproduct.code}}</span>
<span>{{subproduct.tag}}</span>
<span>{{subproduct.parentTag}}</span>
</div>
</div>
</div>
</body>

select in ng-option does not update

I have the list of data that is coming from backend and I want to update the select value in the view which is not happening for some reason.
I tried ng-selected that does not works efficiently, sometime the model is update spmetimes not.
here is my code, can someone help?
<div class="listitem" ng-repeat="d in data">
{{d.name}}:
<select
ng-model="d.option"
ng-options="d.name for d in options"></select>
</div>
Controller
var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
$scope.options = [{
"id": "id1",
"name": "p1"
}, {
"id": "id2",
"name": "p2"
}];
$scope.data = [{
"name": "data1",
"option": {
"id": "id1",
"name": "p1"
}
}];
});
http://jsfiddle.net/gFCzV/58/
You need to use select as label group by group for value in array track by trackexpr, Read DOCs
ng-options="option.name for option in options track by option.id"
DEMO, However note this will not work in Angualrjs 1.1
You have in your code:
$scope.options = [{
"id": "id1",
"name": "p1"
}, {
"id": "id2",
"name": "p2"
}];
$scope.data = [{
"name": "data1",
"option": {
"id": "id1",
"name": "p1"
}
}];
but Angular doesn't know that first option object used in $scope.options collection is same as option used in $scope.data.
I can suggest two solutions:
In $scope.data keep only option identifier "option": "id1" and in ng-options use d.id as d.name for d in options
In ng-options use "ng-options="d as d.name for d in options" and initialize $scope.data options like "option": $scope.options[0], but since it is coming from backend you may need to fix references manually.
Options 1 is better IMHO.
EDIT: Example JSFIDDLE was created in Angular 1.1, if you use Angular 1.2 or later #Satpal track by answer is also good option (no pun).

How to set a selected option of a dropdown list control using angular JS

I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0" to be selected?
I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.
If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.
You can use track by attribute in your ng-options.
Assume that you have:
variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
You can mention your ng-options as:
ng-options="v.name for v in variants track by v.id"
Hope this helps someone in future.
If you assign value 0 to item.selectedVariant it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
for (var j = 0; j < countryList.length; j++) {
//debugger
if (countryList[j].text == "Australia") {
console.log(countryList[j].text);
countryList[j].isSelected = 'selected';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country" >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>
</select>
try this on an angular framework
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];

Resources