I am trying to load angular "select" with the following code
<select class="span11" ng-model="user.countryOfResidence" ng-options="c.option as c.value for c in countries" required>
Its loads the data into the select but the default selected value is empty.
my countries array is
$scope.countries = [{option:'TL', value:'TIMOR-LESTE'},
{option:'TK', value:'TOKELAU'},
{option:'TJ', value:'TAJIKISTAN'},
{option:'TH', value:'THAILAND'},
{option:'TG', value:'TOGO'},];
if i change 'TL' to 'TIMOR-LESTE', (same string for "option" and "value") it works fine. Can any one kindly tell me what is the problem with my code.
user object is
$scope.user = {
countryOfResidence : $scope.countries[0].value
};
A select populated with ng-options will set the ng-model field to what is specified as the value, not the option
In the example you've given, you're setting user.countryOfResidence to countries[0].value, which in this case is 'TIMOR-LESTE', but the value key is 'TL', so it won't select it by default.
For better readability, I always like to structure my select options with 'label' and 'value' keys, like so:
// Controller
$scope.countries = [
{value:'TL', label:'TIMOR-LESTE'},
{value:'TK', label:'TOKELAU'},
{value:'TJ', label:'TAJIKISTAN'},
{value:'TH', label:'THAILAND'},
{value:'TG', label:'TOGO'}
];
$scope.user = {
countryOfResidence: $scope.countries[0].value
};
};
// View
<select class="span11" ng-model="user.countryOfResidence" ng-options="c.value as c.label for c in countries" required=""></select>
Related
How can I get the object associated to the selected option inside within a dropdown (select)?
Here's my html:
<select ng-model="selSeason" ng-options="season as season.name for season in seasons"></select>
Every season is an object with several properties and I'd need to get the object associated to the selected object (and not only its text or value).
I know ng-repeat has something like (to select name of the 5th season):
element(by.repeater('season in seasons').row(4).column('name'));
Is there something similar for by.options() selector?
Thanks
You can use by.options with evaluate():
var seasonNames = element.all(by.options('season in seasons')).evaluate("season.name");
seasonNames.then(function (values) {
console.log(values); // array of season names is printed
});
You can also filter out the selected option with filter():
var selectedSeasonName = element.all(by.options('season in seasons')).filter(function (option) {
return option.getAttribute("selected").then(function (selected) {
return selected;
});
}).first().evaluate("season.name");
selectedSeasonName.then(function (value) {
console.log(value); // selected season name is printed
});
What you are looking for is the custom by.selectedOption locator.
element(by.selectedOption('model_name'))
For a better description, read this: https://technpol.wordpress.com/2013/12/01/protractor-and-dropdowns-validation/
I ended up evaluating not the selected option but the ng-model associated to the select:
HTML
<select ng-model="selSeason" ng-options="season as season.name for season in seasons"></select>
JS
element(by.model('selSeason')).evaluate('selSeason').then(function(season){
console.log(season.name);
});
Your binding looks good, you can read all the properties easily by using your ng-model variable 'selSeason', see this example
<select ng-model="user"
ng-options="x as x.name for x in users track by x.id"
class="form-control"
ng-required="true">
<option value="">-- Choose User --</option>
</select>
var id = $scope.user.id;
var name = $scope.user.name;
var role = $scope.user.role
For more detail check this
I write dependent comboboxes and faced such problem - how to set initial value? For example, I have a form for adding new records:
Controller.js:
...
$http({
url: '/api/address/fill',
method: 'POST'
}).success(function (data) {
$scope.itemsForLevelOne = data
}).error(function(errorData) {
...
});
$scope.updateOne = function() {
$http({
url: '/api/address/change',
method: "POST",
data: {'tobId' : $scope.itemOne.id}
}).success(function (data) {
$scope.itemsForLevelTwo = data;
}).error(function(errorData) {
...
});
};
...
View.html:
...
<label>Level One</label>
<select class="form-control m-b"
data-role="listview"
data-inset="true"
ng-options="someValue as someValue.tobName for someValue in itemsForLevelOne"
ng-model="itemOne"
x-ng-change="updateOne(itemOne)">
</select>
<label>Level Two</label>
<select class="form-control m-b"
data-role="listview"
data-inset="true"
ng-options="someValue as someValue.tobName for someValue in itemsForLevelTwo"
ng-model="itemTwo"
x-ng-change="updateTwo(itemTwo)">
</select>
...
From the controller I can make call to the server- side (Play Framework in my case) and then extract data from the database and save them.
In the forms of editing and deleting records I should to set the initial values for all select elements.
How can I do it?
AngularJS uses bidirectional binding. The selected option is stored in the ng-model attribute when a selection is made, and it's also read from the ng-model attribute on order to display the correct selection.
So you pick the element to select from the array of options, and initialize the variable corresponding to the ng-model of the select. For example, to have the first element selected, you do
$scope.itemOne = $scope.itemsForLevelOne[0];
You should use ng-repeat instead of ng-options
<select>
<option ng-repeat="someValue as someValue.tobName for someValue in itemsForLevelTwo" ng-selected="expression_to_be_evaluated"
</select>
ng-repeat with the option tag, gives you more control than ng-options.
What JB said, but remember it is IMPERATIVE that the values match between the object that you pass to the ng-model and the list values themselves; In your case:
$scope.itemOne = someValue;
$scope.itemTwo = someValue2;
someValue and someValue2 NEED to match up with a corresponding option value, or else you will end up with the dreaded empty first box.
Another solution would to add a default chooser option which instructs the user to choose an option:
...
<label>Level One</label>
<select class="form-control m-b"
data-role="listview"
data-inset="true"
ng-options="someValue as someValue.tobName for someValue in itemsForLevelOne"
ng-model="itemOne"
x-ng-change="updateOne(itemOne)">
<option>Please Select An Item</option>
</select>
...
This way, the person filling out the form will never select an option involuntarily. This default option, because it has no value, will disappear when a selection is made.
Let's say that I have list of countries and each country has a list of states/regions. So there are two selects. First to select country, and when country changes I want to trigger binding of the states select. How do you link these two controls to trigger binding of the states select when country changes?
<select id="countries"
data-ng-model="vm.permanentAddress.countryCode"
data-ng-options="country.code for country in vm.form.countries">
</select>
<select data-ng-model="vm.permanentAddress.stateCode"
data-ng-options="state.value for state in vm.getStatesForCountry(vm.permamentAddress.countryCode)">
</select>
UPDATE:
I was probably not explicit in my question as to what I want to do. I do not want to create any new properties that are then watched by angular for a change. I just want to tell anuglar, hey something has changed, go ahead and re-evaluate the binding for this control.
Is it not possible?
In your controller have something like this:
$scope.setStateOptions = function(country){
$scope.stateOptions = /* whatever code you use to get the states */
}
Then your html can be:
<select id="countries"
data-ng-model="vm.permanentAddress.countryCode"
data-ng-options="country.code for country in vm.form.countries"
data-ng-change="setStateOptions(country)">
</select>
<select
data-ng-model="vm.permanentAddress.stateCode"
data-ng-options="state.value for state in stateOptions">
</select>
May be you should use the jquery chanied select plugin:
http://jquery-plugins.net/chained-selects-jquery-plugin
I have used it for 4 select list chained and it worked fine.
Thx
Here is a working example. You just need to use the ng-change to change the model you have set for the states
You can take advantage of the dynamic nature of JavaScript to bind the key from the first list to the second list. Then you only have to set a default value on the change. If you remove the $watch it will still work, the second select will just default to empty when you switch the category.
Here's my data set-up and watch:
app.controller("myController", ['$scope', function($scope) {
$scope.data = ['shapes', 'colors', 'sizes'];
$scope.data.shapes = ['square', 'circle', 'ellipse'];
$scope.data.colors = ['red', 'green', 'blue'];
$scope.data.sizes = ['small', 'medium', 'large'];
$scope.category = 'colors';
$scope.$watch('category', function () {
$scope.item = $scope.data[$scope.category][0];
});
And here's the HTML:
<div ng-app="myApp" ng-controller="myController">
<select id="categories"
data-ng-model="category"
data-ng-options="category for category in data"></select>
<select id="item"
data-ng-model="item"
data-ng-options="item for item in data[category]"></select>
{{category}}: {{item}}</div>
You can, of course, change this to host complex objects and use keys or other identifiers to switch between the lists. The full fiddle is here: http://jsfiddle.net/jeremylikness/8QDNv/
I am working with AngularJS and I am so new in that.
My aim is fill a tag SELECT with OPTION element from a datasource.
That is what I do basically:
<script>
function LocalizationController($scope, $http) {
$scope.Regions = [
{ ID: "001", DESC: "DESC_1" },
{ ID: "002", DESC: "DESC_2" },
{ ID: "003", DESC: "DESC_3" },
{ ID: "004", DESC: "DESC_4" },
];
$scope.Region = "003";
$scope.init = function () {
$scope.Region = "003";
}
}
</script>
<div ng-controller="LocalizationController" ng-init="init();">
<input type="button" ng-click="Region='002'" value="test">
<select id="region" name="RegionCode" ng-model="Region">
<option ng-repeat="item in Regions" value="{{item.ID}}">{{item.DESC}}</option>
</select>
</div>
Everything works good, the Select is fill of my items,
but I would like to set default value.
How you can see
- I set my object model which is ng-model="Region"
- I set its default value into init() function by $scope.Region = "003";
when the SELECT is loaded I do not why but dafault value is the first one "001"
I also tried to change value manually by
in that case the SELECT gets the right value selection.
Anyone can explain why it does not work?
I know that is a common problem, I am already looked for that,
any solution suggestion to use NG-OPTION, that directive works good,
it can fill my SELECT with my array of object, it can select default value,
very nice but it does not solve my problem because the value into the
the option element id an integer autoincrement which is not what I want.
so in summary:
NG-REPEAT can render the SELECT how I want but default value does not work
NG-OPTIONS can render the SELECT how I want, default value works but the value into option
item cannot be set how I want.
any suggestions?
thanks in advance
EDIT
I found a "solution"
<div ng-controller="LocalizationController" EXCLUDE-ng-init="init();">
<select id="region" onload="alert();angular.element(this).scope().Region='002'" name="RegionCode" ng-model="Region">
<option ng-repeat="item in Regions" value="{{item.ID}}">{{item.DESC}}</option>
{{init();}}
</select>
</div>
I do not like so much but works pretty good:
- ng-init="init();" does not work good
- If we exclude the initialize of default value into ng-init so EXCLUDE-ng-init="init();" and put the initilize when option are loded it works
Have a look at the code blow, I put {{init();}} after ng-repeat. Everithing works good
{{item.DESC}}
{{init();}}
I do not think is the best solution but Works,
1) I have a droopdown fill of my elements
2) The value of option into my list is CORRECT, "001", "002" and not a stupid autoincremental value which is useless.
I hope that can help someone...
THANKS TO EVERYONE TRIED TO HELP ME
Just use ng-options
<select id="region" name="RegionCode" ng-model="Region" ng-options="option.ID as option.DESC for option in Regions">
And do
$scope.init = function () {
$scope.Region = $scope.Regions[2];
}
When you inspect the select box while using ng-options the values for the options will be like 0,1,2,3.., that is auto increment integer as you said. But don't worry about that. Its the value just for showing up there, but once you post your form you will get the right value as you possess, in your case ID.
use ng-options
and in this case if you play with object (not single values) it should be so
$scope.init = function () {
$scope.Region = $scope.Regions[2];
}
I'm using angular-ui's select2 for a fairly simple dropdown. It's backed by a static array of data sitting on my controller's scope. In my controller I have a function that gets called on ng-change of the dropdown so that I can perform some actions when the value changes.
However, what I'm finding is that the ng-model's property gets set as a JSON string rather than an actual javascript object, which makes it impossible to use dot notation to grab properties off of that model.
Here's the function that handles the value of the dropdown getting changed:
$scope.roleTypeChanged = function() {
//fine:
console.log('selectedType is: ', $scope.adminModel.selectedType);
// this ends up being undefined because $scope.adminModel.selectedType is a
// JSON string, rather than a js object:
console.log('selectedType.typeCode is: ', $scope.adminModel.selectedType.typeCode);
}
Here's a plunker of my full example: http://plnkr.co/edit/G39iZC4f7QH05VctY8zG
I've never seen a property that's bound to ng-model do this before, however I'm also fairly new to Angular so it's likely that I'm just doing something wrong here. I can certainly do something like $.parseJSON() to convert the JSON string back to an object, but I'd rather not unless I have to.
Thanks for any help!
You need to use ng-options on your select if you want to have object values. Actually creating the options yourself using an ng-repeat will only allow you to have string values for the various options:
<select ui-select2
ng-model="adminModel.selectedType"
ng-change="roleTypeChanged()"
data-placeholder="Select Role Type" ng-options="type.displayName for type in adminModel.roleTypes">
<option value=""></option>
</select>
http://plnkr.co/edit/UydBai3Iy9GQg6KphhN5?p=preview
Thanks Karl!
I have struggled a day with this
as a note for others having similar problems as I did,
when using an ng-model not accessible and defined in the controller/directive I solved it like this.
//country.Model has Code and Name nodes
* HTML *
<select
name="country" data-ng-model="country.Model"
data-ui-select2=""
data-ng-change="countryChanged(country.Model)" <!--only for test, log to console-->
data-ng-options="country as CodeAndName(country) for country in countries"
data-placeholder="{{placeholderText(country.Model, '- - Select Country - -')}}" >
<option value=""></option>
</select>
* JS *
function controller($scope, $q, $location, $routeParams) {
$scope.countryChanged = function(item) { // for test
console.log('selectedType is: ', item);
};
//returns the item or the text if no item is selected
$scope.placeholderText = function (item, text){
if (item == undefined)
return text;
return $scope.CodeAndName(item);
};
// returns a string for code and name of the item, used to set the placeholder text
$scope.CodeAndName = function (item) {
if (item == undefined)
return '';
return item.Code + ' - ' + item.Name;
};