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'm fairly new to Angular and was wondering how I can update a dropdown after doing an insert and have the new value selected?
I tried the following:
<select class="form-control" ng-model="selectedCompany" ng-change="GetCompany()"
ng-options="company.key as company.value for company in CompanyList">
<option value="">Select a Company</option>
</select>
This populates a list of companies when the page 1st loads and the inserted data is returned to scope + it's id.
To add the new value without refreshing the page, I'm trying the following non-working (almost) code:
var key = $scope.company.id;
var value = $scope.company.name;
$scope.CompanyList.push({ key: value });
$scope.selectedCompany = $scope.company.id;
This seems to add a value to the dropdown, but it's showing up blank. It's also not selecting the blank value (which should be the new company name), any help would be appreciated.
It seems that when you create the new company object, you need to assign the value property which is the display name.
Here's a code snippet:
angular.module("myApp", [])
.controller("testCtrl", function() {
this.companyList = [{
key: 1,
value: "Company A"
}];
var ctrl = this;
this.addCompany = function() {
ctrl.companyList.push({key:2, value:"Company B"});
ctrl.selectedCompany = 2;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="testCtrl as ctrl">
<select class="form-control"
ng-model="ctrl.selectedCompany"
ng-options="company.key as company.value for company in ctrl.companyList">
<option value="" disabled>Select a Company</option>
</select>
<button ng-click="ctrl.addCompany()">
Add company B and select it
</button>
</div>
Ok, so what do we have here?
You're creating your options with the ngOptions directive like this: ng-options="company.key as company.value for company in CompanyList"
That mean that the array $scope.CompanyList must have objects with a key property that will be set to the option value attribute, and a value that will be the option display value (Or label, if you prefer to call it that way).
What you were doing wrong: You added an object with only one property named key and set its value with the value variable: $scope.CompanyList.push({ key: value });
How should you fix it: You need to append object(s) with a key and a value like so: $scope.CompanyList.push({ key: key, value: value });
The following line push an object, which has a property name "key" set to value:
$scope.CompanyList.push({ key: value });
The result will be:
{'key': $scope.company.name}
You may change it to:
$scope.CompanyList.push({key: key, value: value});
Which will result in:
{ 'key': $scope.company.id, 'value': $scope.company.name }
So first the ng change is not triggering the search function. And the ng selected also no selecting the id = 0 option, is putting a blank option instead of selecting option 1. This is all contain the same in app and same controller.
Any ideas?
Code here
<select ng-model="OrderBy" ng-change="Search(true)">
<option ng-repeat="x in OrderByList" value="{{x.ID}}"
ng-selected="{{ x.ID == 0 }}">{{x.Name}}</option>
</select>
$scope.OrderByList = [
{ Name: "option1", ID: 0 },
{ Name: "option2", ID: 2 }
];
$scope.Search = function (x) {
// Code
};
Thanks.
You should look into ng-options, it'll probably work better for you.
<select
ng-model="OrderBy"
ng-change="Search(true)"
ng-options="x.ID as x.Name for x in OrderByList">
</select>
This will probably fix both issues.
In your controller do this:
$scope.OrderBy = 0;
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 an javascript object as follows in my controller:
$scope.options = [
{
"actualValue": "age",
"displayValue": "Age"
},
{
"actualValue": "maiden",
"displayValue": "Maiden Name"
}
];
Now, I am displaying a select element in which the options of the element will be the values in the "displayValue" property written above:
<select ng-options="entry.displayValue for entry in options" ng-model="biodata">
<options>-- Select a BioData Option --</option>
</select>
Now, my problem is that the ng-model for the select element above when the user select a value from the dropdown is the "displayValue" property. I wish that the ng-model be the "actualValue" property.
How can I achieve this?
<select ng-options="entry.actualValue as entry.displayValue for entry in options"></select>
Fiddle: http://jsfiddle.net/rzV65/
Already answered here: How do I set the value property in AngularJS' ng-options?