Set default value inside ngSelect - angularjs

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

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>

ng change and ng select not working

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;

Angularjs ng-options with an array of key-pair

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

angularjs ngRepeat orderBy when property key has spaces

I'm getting some data in JSON format which has spaces in the some of the keys:
[
{
"PlainKey": "SomeValue",
"Spaced Key": "SomeValue"
},
{
"PlainKey": "SomeValue2",
"Spaced Key": "SomeValue2"
}
]
This happens at some point:
$http.get('https://dl.dropboxusercontent.com/u/80497/htmlTesting/properties/credits.properties' + '?callback=JSON_CALLBACK').then(function (data) {
$scope.credits = data.data;
}, function (error) {
$scope.errorOccured = true;
console.log("Error:");
console.log(error);
});
and then ng-repeat is used to display it, with ordering:
<select ng-model="corder">
<option value="PlainKey">Plain Key</option>
<option value="Spaced Key">Spaced Key</option>
</select>
<li ng-repeat="credit in credits | orderBy:corder" >
.....
</li>
This doesn't work ( I get an exception )
(The PlainKey works because there are no spaces).
I also tried putting the values in ':
<select ng-model="corder">
<option value="'PlainKey'">Plain Key</option>
<option value="'Spaced Key'">Spaced Key</option>
</select>
This seems to change the order, but not correctly.
What Am I missing?
Thanks!
Simplest way, just surround a field name with UTF8 code for quotation mark:
HTML
<li ng-repeat="item in items | orderBy:'\u0022Spaced Key\u0022'">
JS
$scope.orderKey = '\u0022Spaced Key\u0022';
Comments appeared to help so I'm including it as an answer:
One way to sort items with spaces in their object property names is to pass a predicate sort function into orderBy instead of specifying the object property name. The relevant modifications in particular:
HTML:
<li ng-repeat="credit in credits | orderBy:predicate">
JS:
$scope.predicate = function(val) {
// $scope.corder corresponds to the object property name to sort by
return val[$scope.corder];
}
Demonstration Plunker.

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.

Resources