Angularjs ng-options with an array of key-pair - angularjs

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];
}
}]);

Related

pre select a value using ng-options in angular js [duplicate]

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>

Set default value inside ngSelect

I have a a ngSelect with some options in it.
<select data-ng-model="type" data-ng-change="option(type)">
<option data-ng-repeat="type in languages" value="{{type.i18n}}">
{{type.language}}
</option>
</select>
And a Controller
angular.module('navigation', [])
.controller('NavCtrl',['$scope','$translate', function($scope,$translate){
$scope.option = function(type){
console.log(type) //this display the i18n value of languages
$translate.use(type);
}
$scope.languages = [
{ language: "English", i18n: "en_EN"},
{ language: "Swedish", i18n : "se_SE" }
];
}])
I want the ngSelect to have a default option, in my case: "English". I've tried to set it to:
$scope.type = $scope.languages[0].language; // English
$scope.type = $scope.languages[0]; //The whole darn json object.
Help please?
Try this way
<select ng-model="selectedlanguage" ng-change="option(this.selectedlanguage)" ng-options="i.language for i in languages">
</select>
//Js code
angular.module('navigation', [])
.controller('NavCtrl',['$scope','$translate', function($scope,$translate){
$scope.option = function(type){
console.log(type) //this display the i18n value of languages
$translate.use(type);
}
$scope.languages = [
{ language: "English", i18n: "en_EN"},
{ language: "Swedish", i18n : "se_SE" }
];
**$scope.selectedlanguage = $scope.languages[0];**
}])
how about using ngSelected? http://docs.angularjs.org/api/ng/directive/ngSelected
<option ng-selected="$index==0"></option>
or
<option ng-selected="type.language=='English'"></option>
Working example: http://plnkr.co/edit/yv8gew3IDGxjH666UmlC?p=preview
<select data-ng-model="selectedType">
<option data-ng-repeat="lang in languages" value="{{lang.i18n}}">
{{lang.language}}
</option>
</select>
JS:
.controller('NavCtrl',['$scope', function($scope){
$scope.$watch('selectedType', function(type){
if (!type) return;
console.log(type) //this display the i18n value of languages
// $translate.use(type);
});
$scope.languages = [
{ language: "English", i18n: "en_EN"},
{ language: "Swedish", i18n : "se_SE" }
];
$scope.selectedType = $scope.languages[0].i18n;
}]);
Notes:
Have removed the $translate service for ease of reproduction.
Have changed an ng-changed callback to a $watch on the $scope but that is merely aesthetic choice.
The crucial change was that you were choosing the lang.i18n for type but were setting type to lang.language, thus resulting in no matches in the options list.
I don't have enough reputation to comment so I will leave it as an answer.
The Ramesh Rajendran answer is right, but you tried using a different ngOptions syntax.
If you use the label for value in array syntax, then you have to bind the model attribute to the entire object.
If you use the syntax in your comment, which is select as label for value in array then you have to bind the model to the select.
In order words, his example works, and to your example on the comment to work you need to replace $scope.selectedlanguage = $scope.languages[0]; with $scope.selectedlanguage = $scope.languages[0].i18n;
Check the select directive documentation for further information
This worked for me:
$scope.prop = { "values":
[ {name:'hello1',id:1},{name:'hello2',id:2},{name:'hello3',id:3}] };
$scope.selectedValue = 2;
<select ng-model="selectedValue" ng-options="v.id as v.name for v in prop.values">
<option selected value="">Select option</option>
</select>
live example: Plunker

angularjs - pass selected object's other properties on ng-change

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>

Setting default value in select drop-down using Angularjs

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.

Angular ng-repeat filter with predicate function not works as expected

This is my first time playing with AngularJS, and actually, I'm following the getting-started tutorial. It came to my mind that I would tweak the tutorial scripts to my understandings, by just adding a little that was not in the tutorial.
Basically, the phone object used in the tutorial was:
{
"age": 1,
"id": "motorola-xoom",
"imageUrl": "img/phones/motorola-xoom.0.jpg",
"name": "MOTOROLA XOOMâ„¢",
"snippet": "The Next, Next Generation..."
}
What I was trying to do was to add an auto populated select box for order the list:
<select ng-model="orderProp">
<option ng-repeat="(key, value) in phones[0]" value="{{key}}">
{{labels[key]}}
</option>
</select>
and added a model labels to the controller:
$scope.labels = {
"name": "Phone name",
"snippet": "Description",
"age": "Newest",
};
It was working as expected, except that I only wanted to filter the 3 properties above, so I think it would be easy to add a custom predicated function for filtering like this:
$scope.isPhonePropFilterable = function (propName) {
console.log('it DOES NOT get here!!!');
return propName == 'name' || propName != 'snippet' || propName != 'age';
};
and added this to the ng-repeat
<option ng-repeat="(key, value) in phones[0] | filter:isPhonePropFilterable" value="{{key}}">
To my suprise, it was not as easy as I thought, my filter function was not called.
See it here: plunker
Did I do anything wrong?
edited: ng-repeat filter supports filtering array only, not object. The filter function returnes if array param is not an array...
Well, it was my fault. Ng-repeat filter supports array only, it did only mention array in the docs. And checking the filter function, it returned if array param is not an array....

Resources