How to preselect a specific element from dropdown using ng-repeat - javascript

This is my html code:
<select id="selectFileType" ng-model="instance.fileType" required>
<option ng-repeat="(key, value) in fileTypes" id="key" value="{{key}}">{{key}} ({{value}})</option>
</select>
I am using a map of items to fill the list with information - now I want to pre-select a specific element based on the key but all the solutions I found didn`t work.
E.g. I tried to use the id field to use something like:
document.getElementById("A").selected = true;
Does someone have an idea what I should do?
Thanks and have a nice day

Use the ng-selected directive to set your pre-selected option.
angular.module('myApp', [])
.controller('ctrl', function($scope) {
$scope.vm = {
priceTypes: [{
id: 3,
name: 'pound'
},
{
id: 5,
name: 'Yen'
},
{
id: 6,
name: 'dollar'
}
]
};
//select model value
$scope.localModel = {
priceType: $scope.vm.priceTypes[1]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="localModel.priceType">
<option
ng-repeat="item in vm.priceTypes as item"
ng-selected="localModel.priceType.id == item.id"
value="{{item}}"
>{{item.name}}</option>
</select>
<div>
priceType: {{ localModel.priceType }}
</div>
</div>

Related

<select> with ng-model and static options (true/false)

I have a simple select element which I want to use to set a boolean value:
# JS; somewhere inside the controller
var vm = this;
vm.isAdmin = false;
return vm;
# HTML
<select ng-model="formCtrl.isAdmin">
<option ng-value="true">Yes</option>
<option ng-value="false">No</option>
</select>
Unfortunately, when loading the site, nothing is selected.
I know I could use ng-repeat, but I don't want to because it seems unpractical to me.
UPDATE:
While the possible duplicate has basically the same accepted answer (because it's the best way to achieve the desired behaviour), the question itself is different. I actually wanted to use hard-coded options, not ng-options/ng-repeat.
Why don't you use ng-options?
<select ng-model="form.isAdmin" ng-options="o.value as o.name for o in options"></select>
options array in your controller:
$scope.options = [
{ 'name': 'Yes', 'value': true },
{ 'name': 'No', 'value': false }
];
Demo on JSFiddle
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', [function() {
var vm = this;
vm.isAdmin = false;
vm.adminOptions = [{
val: true,
name: 'Yes'
}, {
val: false,
name: 'No'
}];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl as form">
<select ng-model="form.isAdmin" ng-options="opt.val as opt.name for opt in form.adminOptions">
</select>
{{form.isAdmin}}
</div>
</div>
You need to basically use the following syntax for your option tag (use ng-selected):
<select ng-model="formCtrl.isAdmin">
<option ng-value="true" ng-selected="formCtrl.isAdmin">Yes</option>
<option ng-value="false" ng-selected="!formCtrl.isAdmin">No</option>
</select>
Use ng-options:
<select ng-model="form.isAdmin"
ng-options="opt.val as opt.name for opt in [{val:true,name:'Yes'},{val:false,name:'No'}]">
</select>
See this jsfiddle

Handling dropdown in angular js

I have a dropdown with some values :
Apple
Mango
Orange
Grapes
HTML :
<div class="form-group">
<label class="control-label col-sm-20" for="groupz">Role*</label>
<select class="form-control" ng-model="model.selectedRole" name="role" ng-change="GetRole(model.selectedRole)" >
<option value class selected>Select Roles</option>
<option ng-repeat="item in model.roles track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
I want my $scope.selectedRole to be by default as Apple. But later when the user needs to change the value, they can change it from apple to orange or any other fruit name. I have separate service request to fetch the fruits from backend and I write my code in controller as follows.
$scope.GetRole = function() {
$scope.selectedrole = [];
if ($scope.model.selectedRole != null) {
for (var i = 0; i < 1; i++) {
$scope.selectedrole.push($scope.model.selectedRole);
}
}
}
I hope this helps you
JsFiddle
In js
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.selectedrole = ['Apple', 'Mango', 'Orange', 'Grapes'];
$scope.selectRole= $scope.selectedrole[0];
});
In HTML
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectRole" ng-options="role for role in selectedrole">
</select>
</div>
just try : HTML
<select class="form-control select" name="role" id="role" data-ng-model="ctrl.model.selectedRole" data-ng-options="option.name for option in ctrl.model.roles track by option.id"></select>
in your contoller
$scope.model = {
roles: [{
id: '1',
name: 'Apple'
}, {
id: '2',
name: 'Orange'
}, {
id: '3',
name: 'Mango'
}],
selectedRole: {
id: '1',
name: 'Apple'
} //This sets the default value of the select in the ui
};
Then assign the first array element to selectedrole containing the array of values(Apple Mango Orange Grapes).
If you want the default to be apple and the array is ordered:
array = [Apple, Mango, Orange, Grapes]
Your model needs to be set to selectedRole:
data-ng-model="selectedRole"
In your controller, set:
selectedRole = array[0]
angular will take care of the rest of the data manipulation.
I hope this helps. Please provide more information for a clearer answer
Thanks
Handling a select element i.e. a drop down list in AngularJS is pretty simple.
Things you need to know is that you bind it to an array or a collection to generate the set of option tags using the ng-options or the ng-repeat directives which is bound to the data source on your $scope and you have a selected option which you need to retrieve as it is the one the user selects, it can be done using the ng-model directive.
If you want to set the selected option on the page load event, then you have to set the appropriate object or value (here it is the fruit id) which you are retrieving from data binding using the as clause in the ng-options directive as shown in the below embedded code snippet
ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
or set it to the value of the value attribute when using the ng-repeat directive on the option tag i.e. set data.model to the appropriate option.value
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
angular
.module('fruits', [])
.controller('FruitController', FruitController);
function FruitController() {
var vm = this;
var fruitInfo = getFruits();
vm.fruits = fruitInfo.fruits;
vm.selectedFruitId = fruitInfo.selectedFruitId;
vm.onFruitChanged = onFruitChanged;
function getFruits() {
// get fruits and selectedFruitId from api here
var fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Mango' },
{ id: 3, name: 'Banana' },
{ id: 4, name: 'Orange' }
];
var fruitInfo = {
fruits: fruits,
selectedFruitId: 1
};
return fruitInfo;
}
function onFruitChanged(fruitId) {
// do something when fruit changes
console.log(fruitId);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fruits">
<div ng-controller="FruitController as ctrl">
<select ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
ng-model="ctrl.selectedFruitId"
ng-change="ctrl.onFruitChanged(ctrl.selectedFruitId)">
<option value="">Select Fruit</option>
</select>
</div>
</div>
Check the Example section here for more information.

How to populate the list of all countries into select multiple and then determine which ones were selected

In my Angular app I have a task of presenting to the user a "select multiple" list of ALL countries, and, after they make their multiple selections, to be able to determine which countries were selected.
I understand how to use ng-repeat inside of the tag, but, I don't know how to properly populate my $scope.countries model array in my controller. ( my only guess is to have the entire country list in a database, and then use ng-init to push all records onto the $scope.countries array, but I'm not sure if this is the best way to do this)
My second challenge is to be able to iterate over the select object, after one or more items were selected, and determine which once were selected.
Currently, my select looks like this:
<div class="form-group">
<label for="selectbasic">What country is the data for</label>
<div>
<select type="text" class="form-control multiselect multiselect-icon" multiple="multiple" ng-model="SelectedCountries">
<option ng-repeat="country in countries">
{{country.name}}
</option>
</select>
</div>
</div>
And my controller looks like this:
$scope.countries = [
{
name: "US"
},
{
name: "UK"
},
{
name: "France"
}
];
Try this: http://jsfiddle.net/tarris/6S2Nk/
Here's the gist of it:
<div ng-app="myApp">
<div ng-app="myApp" ng-controller="con">
<div ng-repeat="item in countries">
<input type='checkbox' ng-model="item.checked" />{{item.name}}
</div>
<button ng-click="checkit()">Check it</button>
</div>
</div>
and the javascript:
var myApp = angular.module('myApp', []);
myApp.controller('con', ['$scope', function($scope){
$scope.countries = [
{id:'us', name: 'United States', checked: false},
{id:'fr', name: 'France', checked: false},
{id:'sw', name: 'Sweden', checked: true}
];
$scope.checkit = function(){
var list = [];
for(var p in $scope.countries){
if($scope.countries[p].checked){
list.push($scope.countries[p].name);
}
}
alert(list);
};
}]);

Name array with ng-model

I have an add button that uses a directive to add-to a table's (.estimates) tbody:
function EstimateCtrl( $scope, $compile ) {
$scope.services = [
{ 'value': 'c', 'name': 'Standard Courier' },
{ 'value': 'xc', 'name': 'Express Courier' },
{ 'value': 'cc', 'name': 'Country Courier' }
]
$scope.add = function() {
angular.element('.estimates tbody').append( $compile('<tr estimate></tr>')($scope) );
}
}
angular.module('dashboard', [])
.directive('estimate', function() {
return {
restrict: 'A',
template: '<td><input type="text" placeholder="Suburb"/></td><td><select ng-model="estimate.service" ng-options="service.value as service.name for service in services" class="form-control"></select></td><td>$0.00</td><td><button type="button" class="remove">x</button></td>',
link: function( scope, element, attrs ) {
element.find('.remove').bind('click', function() {
element.closest('tr').remove();
});
}
}
});
How can I have an element array using ng-model in angularjs? For example:
<select name="foo[]"></select>
to
<select ng-model="foo[]"></select>
I've been digging around for a day and half but I can't seem to catch a break. I was hoping that maybe someone can point me in the right direction. Thank you very much for any help.
Edit: Here is the link to the plunker I'm sure after seeing this everyone is going know what I'm on about:
http://plnkr.co/edit/JlYB9P0vyAqghOmeNYh4
Edit2: Let's see if I can give you all another example to show you what I'm after
<form method="POST" action="">
<!-- I was attempting to do ng-model="estimate.service[]" but of course this doesn't work -->
<select name="estimate[service][]">
<option value="foor">Foo</option>
<option value="bar">Bar</option>
</select>
<select name="estimate[service][]">
<option value="foor">Foo</option>
<option value="bar">Bar</option>
</select>
<select name="estimate[service][]">
<option value="foor">Foo</option>
<option value="bar">Bar</option>
</select>
<input type="submit" value="Submit"/>
</form>
<?php
if ( $_POST )
{
print_r( $_POST['estimate']['service'] );
}
?>
Output
Ohrighty! I managed to find a work around.
I have abandoned directives and did it another way, here is my working code:
HTML:
<div ng-controller="Ctrl">
<table>
<tbody ng-repeat="service in estimate.services">
<tr>
<td><input type="text" placeholder="Suburb"/></td>
<td>
<select ng-model="estimate.services[service.name]" ng-options="option.value as option.name for option in options" class="form-control"></select>
</td>
<td>$0.00</td>
<td><button type="button" class="remove">x</button></td>
</tr>
</tbody>
</table>
</div>
JavaScript:
function Ctrl( $scope, $compile ) {
$scope.estimate.services = [
{ name: 'service1', value: '' }
];
$scope.options = [
{ name: 'Option 1', value: 'opt1' },
{ name: 'Option 2', value: 'opt2' },
{ name: 'Option 3', value: 'opt3' }
];
$scope.add = function() {
$scope.estimate.services.push({
name: 'service' + ($scope.estimate.services.length + 1),
value: ''
});
};
}
EDITED:
Ok lets say you have two arrays of configurable options:
options1=[...]
options2=[...]
Now if I understand correctly you want a select box that enables yout to select one set of them right? So first you need to enclose both of them in another array or as mentioned before another object.
So lets use an object (I can provide an array example as well)
var $scope.myOptions ={'LabelForOptions1' : options1, 'LabelForOptions2' : options2}
Next we need a place to store the options that were choosen
$scope.selectedOptions = {};
and lastly the select box itself
<select ng-model="selectedOptions" ng-options="value as key for (key,value) in myOptions"></select>
Note that the options1 and options2 variable could be also a single value and the example would still work
COMPLETE SOLUTION TO PROBLEM:
I assume this is your model:
function MyController($scope) {
$scope.options1 = ['Foo1','Bar1'];
$scope.options2 = ['Foo2','Bar2'];
$scope.options3 = ['Foo3','Bar3'];
$scope.allOptions = [$scope.options1, $scope.options2, $scope.options3];
$scope.selectedOptions = ["none","none","none"];
};
So this would be the solution:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="./js/myAngular.js"></script>
</head>
<body ng-controller="MyController">
<div><select ng-repeat="option_set in allOptions"ng-model="selectedOptions[$index]" ng-options="value for value in option_set">
</select></div>
</body>
</html>
Working example:
http://jsfiddle.net/qGRQF/11/

How to have a default option in Angular.js select box

I have searched Google and can't find anything on this.
I have this code.
<select ng-model="somethingHere"
ng-options="option.value as option.name for option in options"
></select>
With some data like this
options = [{
name: 'Something Cool',
value: 'something-cool-value'
}, {
name: 'Something Else',
value: 'something-else-value'
}];
And the output is something like this.
<select ng-model="somethingHere"
ng-options="option.value as option.name for option in options"
class="ng-pristine ng-valid">
<option value="?" selected="selected"></option>
<option value="0">Something Cool</option>
<option value="1">Something Else</option>
</select>
How is it possible to set the first option in the data as the default value so you would get a result like this.
<select ng-model="somethingHere" ....>
<option value="0" selected="selected">Something Cool</option>
<option value="1">Something Else</option>
</select>
You can simply use ng-init like this
<select ng-init="somethingHere = options[0]"
ng-model="somethingHere"
ng-options="option.name for option in options">
</select>
If you want to make sure your $scope.somethingHere value doesn't get overwritten when your view initializes, you'll want to coalesce (somethingHere = somethingHere || options[0].value) the value in your ng-init like so:
<select ng-model="somethingHere"
ng-init="somethingHere = somethingHere || options[0].value"
ng-options="option.value as option.name for option in options">
</select>
Try this:
HTML
<select
ng-model="selectedOption"
ng-options="option.name for option in options">
</select>
Javascript
function Ctrl($scope) {
$scope.options = [
{
name: 'Something Cool',
value: 'something-cool-value'
},
{
name: 'Something Else',
value: 'something-else-value'
}
];
$scope.selectedOption = $scope.options[0];
}
Plunker here.
If you really want to set the value that will be bound to the model, then change the ng-options attribute to
ng-options="option.value as option.name for option in options"
and the Javascript to
...
$scope.selectedOption = $scope.options[0].value;
Another Plunker here considering the above.
Only one answer by Srivathsa Harish Venkataramana mentioned track by which is indeed a solution for this!
Here is an example along with Plunker (link below) of how to use track by in select ng-options:
<select ng-model="selectedCity"
ng-options="city as city.name for city in cities track by city.id">
<option value="">-- Select City --</option>
</select>
If selectedCity is defined on angular scope, and it has id property with the same value as any id of any city on the cities list, it'll be auto selected on load.
Here is Plunker for this:
http://plnkr.co/edit/1EVs7R20pCffewrG0EmI?p=preview
See source documentation for more details:
https://code.angularjs.org/1.3.15/docs/api/ng/directive/select
I think, after the inclusion of 'track by', you can use it in ng-options to get what you wanted, like the following
<select ng-model="somethingHere" ng-options="option.name for option in options track by option.value" ></select>
This way of doing it is better because when you want to replace the list of strings with list of objects you will just change this to
<select ng-model="somethingHere" ng-options="object.name for option in options track by object.id" ></select>
where somethingHere is an object with the properties name and id, of course. Please note, 'as' is not used in this way of expressing the ng-options, because it will only set the value and you will not be able to change it when you are using track by
The accepted answer use ng-init, but document says to avoid ng-init if possible.
The only appropriate use of ngInit is for aliasing special properties
of ngRepeat, as seen in the demo below. Besides this case, you should
use controllers rather than ngInit to initialize values on a scope.
You also can use ng-repeat instead of ng-options for your options. With ng-repeat, you can use ng-selected with ng-repeat special properties. i.e. $index, $odd, $even to make this work without any coding.
$first is one of the ng-repeat special properties.
<select ng-model="foo">
<option ng-selected="$first" ng-repeat="(id,value) in myOptions" value="{{id}}">
{{value}}
</option>
</select>
---------------------- EDIT ----------------
Although this works, I would prefer #mik-t's answer when you know what value to select, https://stackoverflow.com/a/29564802/454252, which uses track-by and ng-options without using ng-init or ng-repeat.
This answer should only be used when you must select the first item without knowing what value to choose. e.g., I am using this for auto completion which requires to choose the FIRST item all the time.
My solution to this was use html to hardcode my default option. Like so:
In HAML:
%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
%option{:value => "", :selected => "selected"}
BC & ON
In HTML:
<select ng-model="province" ng-options="province as province for province in summary.provinces" chosen="chosen-select" data-placeholder="BC & ON">
<option value="" selected="selected">BC & ON</option>
</select>
I want my default option to return all values from my api, that's why I have a blank value. Also excuse my haml. I know this isn't directly an answer to the OP's question, but people find this on Google. Hope this helps someone else.
Use below code to populate selected option from your model.
<select id="roomForListing" ng-model="selectedRoom.roomName" >
<option ng-repeat="room in roomList" title="{{room.roomName}}" ng-selected="{{room.roomName == selectedRoom.roomName}}" value="{{room.roomName}}">{{room.roomName}}</option>
</select>
Depending on how many options you have, you could put your values in an array and auto-populate your options like this
<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
<option value="">Pick a Number</option>
</select>
In my case, I was need to insert a initial value only to tell to user to select an option, so, I do like the code below:
<select ...
<option value="" ng-selected="selected">Select one option</option>
</select>
When I tryed an option with the value != of an empty string (null) the option was substituted by angular, but, when put an option like that (with null value), the select apear with this option.
Sorry by my bad english and I hope that I help in something with this.
Using select with ngOptions and setting a default value:
See the ngOptions documentation for more ngOptions usage examples.
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
selectedOption: {id: '2', name: 'Option B'} //This sets the default value of the select in the ui
};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<body ng-app="defaultValueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
plnkr.co
Official documentation about HTML SELECT element with angular data-binding.
Binding select to a non-string value via ngModel parsing / formatting:
(function(angular) {
'use strict';
angular.module('nonStringSelect', [])
.run(function($rootScope) {
$rootScope.model = { id: 2 };
})
.directive('convertToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(val) {
return parseInt(val, 10);
});
ngModel.$formatters.push(function(val) {
return '' + val;
});
}
};
});
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>
<body ng-app="nonStringSelect">
<select ng-model="model.id" convert-to-number>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
{{ model }}
</body>
plnkr.co
Other example:
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.availableOptions = [
{ name: 'Apple', value: 'apple' },
{ name: 'Banana', value: 'banana' },
{ name: 'Kiwi', value: 'kiwi' }
];
$scope.data = {selectedOption : $scope.availableOptions[1].value};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<body ng-app="defaultValueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<select ng-model="data.selectedOption" required ng-options="option.value as option.name for option in availableOptions"></select>
</form>
</div>
</body>
jsfiddle
This worked for me.
<select ng-model="somethingHere" ng-init="somethingHere='Cool'">
<option value="Cool">Something Cool</option>
<option value="Else">Something Else</option>
</select>
In response to Ben Lesh's answer, there should be this line
ng-init="somethingHere = somethingHere || options[0]"
instead of
ng-init="somethingHere = somethingHere || options[0].value"
That is,
<select ng-model="somethingHere"
ng-init="somethingHere = somethingHere || options[0]"
ng-options="option.name for option in options track by option.value">
</select>
In my case since the default varies from case to case in the form.
I add a custom attribute in the select tag.
<select setSeletected="{{data.value}}">
<option value="value1"> value1....
<option value="value2"> value2....
......
in the directives I created a script that checks the value and when angular fills it in sets the option with that value to selected.
.directive('setSelected', function(){
restrict: 'A',
link: (scope, element, attrs){
function setSel=(){
//test if the value is defined if not try again if so run the command
if (typeof attrs.setSelected=='undefined'){
window.setTimeout( function(){setSel()},300)
}else{
element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);
}
}
}
setSel()
})
just translated this from coffescript on the fly at least the jist of it is correct if not the hole thing.
It's not the simplest way but get it done when the value varies
Simply use ng-selected="true" as follows:
<select ng-model="myModel">
<option value="a" ng-selected="true">A</option>
<option value="b">B</option>
</select>
This working for me
ng-selected="true"
I would set the model in the controller. Then the select will default to that value. Ex:
html:
<select ng-options="..." ng-model="selectedItem">
Angular controller (using resource):
myResource.items(function(items){
$scope.items=items;
if(items.length>0){
$scope.selectedItem= items[0];
//if you want the first. Could be from config whatever
}
});
If you are using ng-options to render you drop down than option having same value as of ng-modal is default selected.
Consider the example:
<select ng-options="list.key as list.name for list in lists track by list.id" ng-model="selectedItem">
So option having same value of list.key and selectedItem, is default selected.
I needed the default “Please Select” to be unselectable. I also needed to be able to conditionally set a default selected option.
I achieved this the following simplistic way:
JS code:
// Flip these 2 to test selected default or no default with default “Please Select” text
//$scope.defaultOption = 0;
$scope.defaultOption = { key: '3', value: 'Option 3' };
$scope.options = [
{ key: '1', value: 'Option 1' },
{ key: '2', value: 'Option 2' },
{ key: '3', value: 'Option 3' },
{ key: '4', value: 'Option 4' }
];
getOptions();
function getOptions(){
if ($scope.defaultOption != 0)
{ $scope.options.selectedOption = $scope.defaultOption; }
}
HTML:
<select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
<option value="" disabled selected style="display: none;"> -- Please Select -- </option>
</select>
<h1>You selected: {{options.selectedOption.key}}</h1>
I hope this helps someone else that has similar requirements.
The "Please Select" was accomplished through Joffrey Outtier's answer here.
If you have some thing instead of just init the date part, you can use ng-init() by declare it in your controller, and use it in the top of your HTML.
This function will work like a constructor for your controller, and you can initiate your variables there.
angular.module('myApp', [])
.controller('myController', ['$scope', ($scope) => {
$scope.allOptions = [
{ name: 'Apple', value: 'apple' },
{ name: 'Banana', value: 'banana' }
];
$scope.myInit = () => {
$scope.userSelected = 'apple'
// Other initiations can goes here..
}
}]);
<body ng-app="myApp">
<div ng-controller="myController" ng-init="init()">
<select ng-model="userSelected" ng-options="option.value as option.name for option in allOptions"></select>
</div>
</body>
<!--
Using following solution you can set initial
default value at controller as well as after change option selected value shown as default.
-->
<script type="text/javascript">
function myCtrl($scope)
{
//...
$scope.myModel=Initial Default Value; //set default value as required
//..
}
</script>
<select ng-model="myModel"
ng-init="myModel= myModel"
ng-options="option.value as option.name for option in options">
</select>
try this in your angular controller...
$somethingHere = {name: 'Something Cool'};
You can set a value, but you are using a complex type and the angular will search key/value to set in your view.
And, if does not work, try this :
ng-options="option.value as option.name for option in options track by option.name"
I think the easiest way is
ng-selected="$first"

Categories

Resources