I am having problems in getting an array inside of an object into an ng-options.
I have following array of objects with inside another array:
$scope.array = [{name: "jan", ar=["car", "bus", "bike"]}, {name: "tom", ar=["milk", "water", "bike", "walking"]}, {name: "kim", ar=["star", "car"]}]
I would like to make a select with the options jan, tom and kim. But that isn't a problem:
<select ng-options="o.name for o in array" ng-model="choosen.nOption">
however when they choose an option a new select should start with as options the array ar from that name:
<select ng-if="choosen.nOption!=undefined" ng-options="o.ar for o in array.ar | filter: {name: choosen.nOption}">
Can anyone help how I could get the values of the inside array?
You can find a fiddler at https://jsfiddle.net/brokenhip/phxyap8a/
Solution:
https://jsfiddle.net/brokenhip/phxyap8a/2/
<select ng-options="o.name for o in arrayA" ng-model="choosen.nOption"></select>
<select ng-if="choosen.nOption!=undefined" ng-options="o for o in choosen.nOption.ar" ng-model="choosen.nOption2"> </select>
So i found an easy way is to use $watch to see when the first select change.
In your controller add this :
$scope.$watch('choosen.nOption',function(newVal){
$scope.choosenOption = newVal['ar'];
console.log($scope.choosenOption); // check in your console
});
And in your HTML, you don't need a filter:
<select ng-if="choosen.nOption!=undefined" ng-options="opt for opt in choosenOption" ng-model="choosen.nOption2"> </select>
Related
I've seen the documentation of the Angular select directive here: http://docs.angularjs.org/api/ng.directive:select.
I can't figure how to set the default value. This is confusing:
select as label for value in array
Here is the object:
{
"type": "select",
"name": "Service",
"value": "Service 3",
"values": [ "Service 1", "Service 2", "Service 3", "Service 4"]
}
The html (working):
<select><option ng-repeat="value in prop.values">{{value}}</option></select>
and then I'm trying to add an ng-option attribute inside the select element to set prop.value as the default option (not working).
ng-options="(prop.value) for v in prop.values"
What am i doing wrong?
So assuming that object is in your scope:
<div ng-controller="MyCtrl">
<select ng-model="prop.value" ng-options="v for v in prop.values">
</select>
</div>
function MyCtrl($scope) {
$scope.prop = {
"type": "select",
"name": "Service",
"value": "Service 3",
"values": [ "Service 1", "Service 2", "Service 3", "Service 4"]
};
}
Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g
The angular documentation for select* does not answer this question explicitly, but it is there. If you look at the script.js, you will see this:
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // Default the color to red
}
This is the html:
<select ng-model="color" ng-options="c.name for c in colors"></select>
This seems to be a more obvious way of defaulting a selected value on an <select> with ng-options. Also it will work if you have different label/values.
* This is from Angular 1.2.7
This answer is more usefull when you are bringing data from a DB, make modifications and then persist the changes.
<select ng-options="opt.id as opt.name for opt in users" ng-model="selectedUser"></select>
Check the example here:
http://plnkr.co/edit/HrT5vUMJOtP9esGngbIV
<select name='partyid' id="partyid" class='span3'>
<option value=''>Select Party</option>
<option ng-repeat="item in partyName" value="{{item._id}}" ng-selected="obj.partyname == item.partyname">{{item.partyname}}
</option>
</select>
If your array of objects are complex like:
$scope.friends = [{ name: John , uuid: 1234}, {name: Joe, uuid, 5678}];
And your current model was set to something like:
$scope.user.friend = {name:John, uuid: 1234};
It helped to use the track by function on uuid (or any unique field), as long as the ng-model="user.friend" also has a uuid:
<select ng-model="user.friend"
ng-options="friend as friend.name for friend in friends track by friend.uuid">
</select>
I struggled with this for a couple of hours, so I would like to add some clarifications for it, all the examples noted here, refers to cases where the data is loaded from the script itself, not something coming from a service or a database, so I would like to provide my experience for anyone having the same problem as I did.
Normally you save only the id of the desired option in your database, so... let's show it
service.js
myApp.factory('Models', function($http) {
var models = {};
models.allModels = function(options) {
return $http.post(url_service, {options: options});
};
return models;
});
controller.js
myApp.controller('exampleController', function($scope, Models) {
$scope.mainObj={id_main: 1, id_model: 101};
$scope.selected_model = $scope.mainObj.id_model;
Models.allModels({}).success(function(data) {
$scope.models = data;
});
});
Finally the partial html model.html
Model: <select ng-model="selected_model"
ng-options="model.id_model as model.name for model in models" ></select>
basically I wanted to point that piece "model.id_model as model.name for model in models" the "model.id_model" uses the id of the model for the value so that you can match with the "mainObj.id_model" which is also the "selected_model", this is just a plain value, also "as model.name" is the label for the repeater, finally "model in models" is just the regular cycle that we all know about.
Hope this helps somebody, and if it does, please vote up :D
<select id="itemDescFormId" name="itemDescFormId" size="1" ng-model="prop" ng-change="update()">
<option value="">English(EN)</option>
<option value="23">Corsican(CO)</option>
<option value="43">French(FR)</option>
<option value="16">German(GR)</option>
Just add option with empty value. It will work.
DEMO Plnkr
An easier way to do it is to use data-ng-init like this:
<select data-ng-init="somethingHere = options[0]" data-ng-model="somethingHere" data-ng-options="option.name for option in options"></select>
The main difference here is that you would need to include data-ng-model
The ng-model attribute sets the selected option and also allows you to pipe a filter like orderBy:orderModel.value
index.html
<select ng-model="orderModel" ng-options="option.name for option in orderOptions"></select>
controllers.js
$scope.orderOptions = [
{"name":"Newest","value":"age"},
{"name":"Alphabetical","value":"name"}
];
$scope.orderModel = $scope.orderOptions[0];
If anyone is running into the default value occasionally being not populated on the page in Chrome, IE 10/11, Firefox -- try adding this attribute to your input/select field checking for the populated variable in the HTML, like so:
<input data-ng-model="vm.x" data-ng-if="vm.x !== '' && vm.x !== undefined && vm.x !== null" />
Really simple if you do not care about indexing your options with some numeric id.
Declare your $scope var - people array
$scope.people= ["", "YOU", "ME"];
In the DOM of above scope, create object
<select ng-model="hired" ng-options = "who for who in people"></select>
In your controller, you set your ng-model "hired".
$scope.hired = "ME";
It's really easy!
Just to add up, I did something like this.
<select class="form-control" data-ng-model="itemSelect" ng-change="selectedTemplate(itemSelect)" autofocus>
<option value="undefined" [selected]="itemSelect.Name == undefined" disabled="disabled">Select template...</option>
<option ng-repeat="itemSelect in templateLists" value="{{itemSelect.ID}}">{{itemSelect.Name}}</option></select>
The following code works. My question is whether this is the right way to do it.
The variable devices is an array of objects and when the user selects one the variable selDev gets set to one of those objects. If I make selDev the model via the ng-model attribute then it gets a string, not the original model.
<p>
<label>Device Id:</label>
<select ng-model="selDevIndex"
ng-change="selDev = devices[selDevIndex]">
<option value="">(no device)</option>
<option ng-repeat="device in devices "
value="{{$index}}">
{{device.id}}: {{device.type}} {{device.mfr}}
{{device.serial}}
</option>
</select>
</p>
I find this a little clumsy due to the inclusion of the $index reference. Also this technique would not work if devices was an object an not an array. Is there a better way?
You can use ng-options
HTML:
<select ng-model="selectedModel"
ng-options="device as device.text for device in devices track by device.id">
</select>
CONTROLLER:
$scope.selectedModel;
$scope.devices = [{
id: 1,
text: "Device1"
}, {
id: 2,
text: "Device2"
}];
Check this jsFiddle
If you have to loop over an object instead of an array, check this post
I'm having below array. I'm trying different ng-options but no use. How to render in Drop down using Angularjs ng-options?
getLanguages:
[0: Object: Key:"en" Value:"English", 1: Object: Key:"fr" Value:"France"]
<select ng-options="language.Object.Value for language in getLanguages track by language.Object.Value"/>
<select data-ng-model="vm.model">
<option data-ng-repeat="language in getLanguages" value="{{language.Object.Key}}">{{language.Object.Value}}</option>
</select>
I got Answer:
<select class="form-control" data-ng-model="vm.model" >
<option data-ng-repeat="language in vm.getLanguages()" value="{{language.Key}}">{{language.Value}}</option>
</select>
Try ng-options = "language.Object.Key as language.Object.Value for language in getLanguages()"
Really the answer is a combination of both David and Stark's answers above.
First you need to make sure your controller is correctly returning the languages, as Stark indicated in his answer.
For example, it should include something like:
$scope.languages = [
{ key : "en",
value : "English" },
{ key : "fr",
value : "French" }];
Then you can populate your <select> options using those languages. As David pointed out, the correct syntax would be similar to the following:
<select ng-model="model.language"
ng-options="language.key as language.value for language in languages">
What this syntax is saying is "show the 'value' in the drop down and map it to the 'key' for each 'language' in the collection returned by the 'languages' variable in the scope." So the drop down will show "English", "French", etc., and when you select one, it will set the model value to "en", "fr", etc.
Here is a working Plunkr showing the above in action.
angular.module('app', []).controller("controllername", ["$scope", function($scope) {
$scope.getLanguages = [
{"en":"English"},
{"fr":"French"}
];
$scope.getKey = function(getLanguages) {
return Object.keys(getLanguages)[0];
}
}]);
I have a simple model : $scope.user = {email: "", birth_month: 0}
Binding user input to email is easy :
<input type="email" ... ng-model="user.email">
However I would like to have a <select> list showing months as "January", "February" etc but directly binding to user.birth_month as integer
I understand that I can do :
$scope.months = [{name: "January", value: 0}, {name: "February", value: 1} ...]
and
<select ng-model=monthObj ng-options="month as month.name for month in months>
</select>
In the scope I will then have a pointer to a month object {name, value} and on change I can set the user.birth_month but I feel like I am completely loosing the power of AngularJS here.
Any more direct way to bind user.birth_month with month.value ?
You can simple use ng-init like this
<select ng-init="monthObj = months[user.birth_month]" ng-model="monthObj" ng-options="month as month.name for month in months"></select>
I have an object as below. I have to display this as a drop-down:
var list = [{id:4,name:"abc"},{id:600,name:"def"},{id:200,name:"xyz"}]
In my controller I have a variable that carries a value. This value decided which of the above three items in the array will be selected by default in the drop-down:
$scope.object.setDefault = 600;
When I create a drop-down form item as below:
<select ng-model="object.setDefault" ng-options="r.name for r in list">
I face two problems:
the list is generated as
<option value="0">abc</option>
<option value="1">def</option>
<option value="2">xyz</option>
instead of
<option value="4">abc</option>
<option value="600">def</option>
<option value="200">xyz</option>
No option gets selected by default even though i have ng-model="object.setDefault"
Problem 1:
The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model.
Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?
Problem 2:
Make sure you're using the following ng-options:
<select ng-model="object.item" ng-options="item.id as item.name for item in list" />
And put this in your controller to select a default value:
object.item = 4
When you use ng-options to populate a select list, it uses the entire object as the selected value, not just the single value you see in the select list. So in your case, you'd need to set
$scope.object.setDefault = {
id:600,
name:"def"
};
or
$scope.object.setDefault = $scope.selectItems[1];
I also recommend just outputting the value of $scope.object.setDefault in your template to see what I'm talking about getting selected.
<pre>{{object.setDefault}}</pre>
In View
<select ng-model="boxmodel"><option ng-repeat="lst in list" value="{{lst.id}}">{{lst.name}}</option></select>
JS:
In side controller
$scope.boxModel = 600;
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
This is an old question and you might have got the answer already.
My plnkr explains on my approach to accomplish selecting a default dropdown value. Basically, I have a service which would return the dropdown values [hard coded to test]. I was not able to select the value by default and almost spend a day and finally figured out that I should have set $scope.proofGroupId = "47"; instead of $scope.proofGroupId = 47; in the script.js file. It was my bad and I did not notice that I was setting an integer 47 instead of the string "47". I retained the plnkr as it is just in case if some one would like to see. Hopefully, this would help some one.
<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>
This would get you desired result Dude :) Cheers
Some of the scenarios, object.item would not be loaded or will be undefined.
Use ng-init
<select ng-init="object.item=2" ng-model="object.item"
ng-options="item.id as item.name for item in list"
$scope.item = {
"id": "3",
"name": "ALL",
};
$scope.CategoryLst = [
{ id: '1', name: 'MD' },
{ id: '2', name: 'CRNA' },
{ id: '3', name: 'ALL' }];
<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>
we should use name value pair binding values into dropdown.see the
code for more details
function myCtrl($scope) {
$scope.statusTaskList = [
{ name: 'Open', value: '1' },
{ name: 'In Progress', value: '2' },
{ name: 'Complete', value: '3' },
{ name: 'Deleted', value: '4' },
];
$scope.atcStatusTasks = $scope.statusTaskList[0]; // 0 -> Open
}
<select ng-model="atcStatusTasks" ng-options="s.name for s in statusTaskList"></select>
I could help you out with the html:
<option value="">abc</option>
instead of
<option value="4">abc</option>
to set abc as the default value.