Please tell me if this select statement looks wrong to you. For some reason, every selection in the drop-down reads undefined instead of the username.
View
<select class="form-control" ng-model="filteredUserId" ng-options="users.Id as users.Username for user in users"></select>
Controller
dmUser.GetUsers().then((response) =>
{
$scope.users = response.data;
});
I verified in Postman what the results are. They are list of these kinds of objects:
{
"Id": 123,
"FirstName": "john",
"LastName": "smith",
"Username": "johnsmith",
"EmailAddress": "johnsmith#test.com"
}
I also tried using the following and it actually works...
<select class="form-control" ng-model="filteredUserId">
<option value="0">All</option>
<option ng-repeat="user in users" value="{{user.Id}}">{{user.Username}}</option>
</select>
It's bugging me that the code using the ngOptions doesn't work. What am I missing?
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>
I face a strange problem where I need to show Pre selected data(which also come from server) in select option. The problem that I need to show select option based on key and value option.
<div class="list list-inset">
<span class="input-label">Permisstion</span>
<select ng-model="permisstion" >
<option ng-repeat="(key, value) in Roles" id="{{key}}" value="{{value}}">{{value}}</option>
</select>
</div>
JSON Data
"Roles": {
"21": "Admin",
"22": "Main Manager",
"23": "Branch Manager",
"26": "Side Manager"
}
I don't no how to show Pre selected data in select option and I try a lot but till now I don't get success.
Please help.
Firt, your JSON is not a array of objects. I dont know if work in a <select> by objects atributes... by my other answer you can do something like in below.
Try to use like that:
"Roles" : {
[
{code: 21, name: "Admin"},
{code: 22, name: "Main Manager"},
{code: 23, name: "Branch Manager"},
{code: 24, name: "Side Manager"}
]
}
So the atribute "code" will be my index to the select:
<select ng-options="role.name for role in Roles track by role.code">
<option value="">They see me rollin</option>
</select>
What I do was use track by role.code, as you can watch in this video.
REMEMBER: If code reapet in the array of objects it will break the <select>.
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];
}
}]);
How can I get other properties from loaded json in dropdown / ng-options
On ng-change I also like to pass selected object's campaignType.
How would I able to do that?
My View is looking like this
<div ng-app>
<div ng-controller="cCtrl">
<select ng-model="campaign" ng-options="c.id as c.name for c in campaigns" ng-change="search2(c.campaignType)">
<option value="">-- choose campaign --</option>
</select>
</div>
</div>
My Controller is looking like this
function cCtrl($scope) {
$scope.campaigns = [{
"custID": 1,
"custName": "aaa ",
"msgID": 3,
"msgName": "Email Test Msg",
"id": 2,
"name": "Email Test Campaign",
"description": "Test Campaign",
"campaignType": "Email",
"created": "1374229715",
"isActive": 1,
"isDeleted": 0
}];
$scope.search2 = function (campaignType) {
alert(campaignType); // not working
alert($scope.campaign.campaignType); // not working
//console.log($scope.campaign.campaignType);
}
}
http://jsfiddle.net/webtheveloper/Qgmz7/8/
Instead of passing in a property, you can pass the selected object into the function like this
<select ng-model="campaign" ng-options="c.name for c in campaigns" ng-change="search2(campaign)">
Working Demo
Check this out: http://jsfiddle.net/Qgmz7/9/
You are not in an ngRepeat context. ngOptions works totally different.
ngModel on a <select> will get the value of the <option>, not the whole object. Again, you are not inside an ngRepeat, you don't have access to your objects.
No need to pass the value as parameter, you can get it from $scope. As a matter of fact you don't need ngChange either, you can just $scope.$watch('campaign', ...)
So
$scope.search2 = function () {
console.log($scope.campaign);
}
You can also try it this way (Hack we can say),
<select ng-model="campaign" ng-options="c.id as c.name for c in campaigns" ng-change="search2(campaign,campaigns)">
<option value="">-- choose campaign --</option>
</select>
Basically what this piece of code will do is that it will just pass ng-model along with the whole dropdown list to ng-change.
So in search2 Function, you can just search that ng-model value into that list and get your desired object.
Fiddle for reference : https://jsfiddle.net/vaibhavgavali92/7b7xdyzj/18/
In some cases such as just to display the member value corresponding item selected would not require a call to Controller function. For example if you want to display the campaign type corresponding to selected campaign, it can be written as follow.
<select ng-model="campaign" ng-options="c.name for c in campaigns">
...
<tr><td>Campaign Type:</td><td>{{campaign.campaignType}}</td></tr>
<tr><td>Campaign Description:</td><td>{{campaign.description}}</td></tr>