I can set a dropdown list with default value in angularjs as,
<select name="repeatSelect" id="repeatSelect" ng-model="repeatSelect" ng-init=" repeatSelect = data[0].id">
<option ng-repeat="option in data" value="{{option.id}}">{{option.name}}</option>
</select>
How can I achieve the same using ng-options? I treid with,
<select name="repeatSelect"
id="repeatSelect"
ng-model="repeatSelect"
ng-init=" repeatSelect = option.id"
ng-options="option.name for option in data track by option.id">
</select>
But no use. Sample fiddle is here
Use ng-init to set default value for ng-options.
Here is the: demo
<select name="repeatSelect"
id="repeatSelect"
ng-model="repeatSelect"
ng-init=" repeatSelect = data[0].id"
ng-options="option.id as option.name for option in data">
</select>
All this miss use of ng-init.
From the angular docs:
This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.
Source docs
In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options, angular does the rest.
Essentially when you define the $scope property your select will bind to assign it the default value from your data array. If your data array is from an ajax request, just assign it once you have the data.
.controller('test', ['$scope', function ($scope) {
$scope.data = [{name: 'one', id: 1}, {name: 'two', id: 2},{name: 'three', id: 3}];
$scope.repeatSelect= $scope.data[0];
}]);
There is one caveat to note. If you employ the as key word in your expression you have to assign your ng-model with the actual property your telling it to select.
See full fiddle demoing both: http://jsfiddle.net/kb99gee8/
i have acheieved what you need using your code and ng-options like you mentioned, here is Working Fiddle
Full CODE
<div ng-app="ngrepeatSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect">Angular select:</label>
<select name="repeatSelect"
id="repeatSelect"
ng-model="repeatSelect"
ng-init=" repeatSelect = data[0]"
ng-options="option.name for option in data track by option.id">
</select>
</form>
<br/> <tt>Selected value: {{repeatSelect.id}}</tt>
</div>
</div>
<br/>
I will suggest an example
HTML part
<select class="form-control" ng-model="data.selectedOption" required ng-options="option.name as option.name for option in venueNamelists" ng-change="getmediationRooms(data.selectedOption)"></select>
In my controller
$scope.data = {selectedOption: $scope.venueNamelists[i].name};
the model value should equal to the key,value pair in the venueNamelists.
Related
How can you sort the options in a {select} like this:
<select ng-options="value as name for (value,name) in vm.options" ng-model="vm.selected">
when vm.options is an object (I want to sort by values)?
Context: At some point I needed to add an explicit empty option "" as a valid value. I'd love it to be the first one on the list, but due to how objects work in Javascript I can't get it to cooperate.
You can achieve in the following way
<select ng-options="option.value as option.name for option in vm.options | orderBy:'value'" ng-model="vm.selected"></select>
and if you want to add empty option like 'Select' then
<select ng-options="option.value as option.name for option in vm.options | orderBy:'value'" ng-model="vm.selected">
<option value="" selected>Select</option>
</select>
Please also refer following link
'orderBy' in AngularJs
I have a list of strings with years on it, like:
$scope.years = ["2001", "2002", "2003", ...];
I'm trying to render it on a page inside a select tag, but angular keeps breaking the code, rendering the elements outside the tag.
I have the following in the page:
<select>
<option value="" disabled selected>----</option>
<option ng-repeat="y in years" value="{!y!}">{!y!}</option>
</select>
I does render, but all the option tags that are generated, are outside the select tag. Am I doing something wrong here?
Edit: using AngularJS 1.5.3
You can use ng-options, which is the recommended way in AngularJS, and has a lot of performance improvements over ng-repeat for this case.
It will require you to have ng-model as well. And you can still have your custom "Empty/Select" option.
It will look like this:
<select ng-model="something" name="S"
ng-options="y for y in years">
<option value="" disabled selected>----</option>
</select>
A full working example:
var app = angular.module("TestApp", []).controller("sample", ["$scope",
function($scope) {
$scope.years = ["2001", "2002", "2003"];
}
]);
angular.bootstrap(document, ["TestApp"]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-controller="sample">
<select ng-model="something" name="S" ng-options="y for y in years">
<option value="" disabled selected>----</option>
</select>
</div>
P.S.
I'm assuming the ! in your code is by mistake, if not, you cannot do this transformation in HTML. You better have another array with the formatted results, and watch the original array to update the transformation one.
Use ng-options instead
documentation: https://docs.angularjs.org/api/ng/directive/ngOptions
sample plnkr for you here: https://plnkr.co/edit/tuKBJsxLxdUKcsRvWvax?p=preview
<select ng-model="selectedValue" ng-options="item for item in years"></select>
I am trying to get the value that user selects from my dropdown.
I have
<select ng-model="item" ng-change="vm.getItem()">
<option value="discount">Discount</option>
<option value="{{::item}}"
ng-repeat="item in vm.items"
ng-bind="item.name"
</option>
</select>
In my controller
vm.getItem = function() {
vm.pickedItem = //not sure what to do...
//I need to get the select item
//please noted that the discount is a stand alone option value. I need to get
//that too if user selects it.
}
I don't want to use ng-option as it has some restriction that I don't need. I was hoping to get it from just regular <option> tag.
Thanks for the help!
I would recommend you to use ngOptions
Set up select element with proper model i.e. vm.pickedItem which can be directly used in controller, or you can pass it to your method like vm.getItem(vm.pickedItem)
<select ng-model="vm.pickedItem" ng-change="vm.getItem(vm.pickedItem )">
<option value="discount">Discount</option>
<option value="{{::item}}"
ng-repeat="item in vm.items"
ng-bind="item.name">
</option>
</select>
vm.getItem = function() {
var selectedItem = vm.item;
////vm.item is the bound variable to the dropdown's ng-model directive
}
If you really wanted to use the ng-change event in this scenario, then on your "getItem" event, you should access the model bound to the dropdown's ng-model called "item" as seen in your html markup.
you forgetting to alis your controller in your select
<select ng-model="vm.item" ng-change="vm.getItem()">
In controller
vm.getItem = function() {
console.log(vm.item)
or
console.log(this.item)
}
I have a ng-repeat iterating through an object of country names and country codes. I'm using ng-selected to preselect the USA (840) which works fine. However, when I introduce the ng-model (signup.user["country_code"]) to the select element containing the object I want to bind the selection to, the ng-select appears to be overridden by the signup.user["country_code"] property which by default is empty.
<select ng-model='signup.user["country_code"]'>
<option ng-repeat="country in signup.country" ng-selected='country["country-code"]=="840"' ng-value='{{country["country-code"]}}'>
{{country["name"]}}
</option>
</select>
So just for clearance the below version is successful in preselecting but is no good due to the lack of binding, the above version does bind just fine but ng-selected is overridden.
<select>
<option ng-repeat="country in signup.country" ng-selected='country["country-code"]=="840"' ng-value='{{country["country-code"]}}'>
{{country["name"]}}
</option>
</select>
Here is a snippet from my controller however I doubt it's that useful for solving this issue.
signup.user = {};
countryCodes.success(function(data) {
signup.country = data;
});
So just set country code initially in controller and use ngModel. You should also use ngOptions directive instead of ngRepeat:
signup.user = {country_code: 840};
HTML:
<select ng-model="signup.user.country_code"
ng-options="country['country-code'] as country.name for country in signup.country">
</select>
I don't know how to clear a select-based filter, when limited to one property. This is the data:
$scope.items = [
{'name': 'Adam', 'fruit': 'apple'},
{'name': 'Shelley', 'fruit': 'apple'},
{'name': 'Barbara', 'fruit': 'plum'},
{'name': 'Steve', 'fruit': 'Adam\'s apple'},
{'name': 'Marty Appleton', 'fruit': 'onion'}
];
This is how I want to filter it, searching for the filter's text in item name property:
<select ng-model="select1.name" ng-options="item.name as item.name for item in items">
<option value="">No filter</option>
</select>
<div ng-repeat="item in items | filter:select1">
{{ item.name }}: {{ item.fruit }}
</div>
When I select one of the options, the list is filtered as expected. But when after that I select the empty "No filter" option again, the list shown is empty. It works perfectly well if I don't limit the filter to one property, i.e. use ng-model="select1" instead of ng-model="select1.name". It also works if I use a text input instead.
Here's a working example of this in action -- you'll notice that you cannot clear the filter with the bottom-right select, but you can with all other elements.
http://codepen.io/anon/pen/vLHqa
I'm lost. What am I doing wrong?
Change to:
<select class="problem" ng-model="select1" ng-options="item.name for item in items">
It's will be work.
http://codepen.io/anon/pen/qroJp
The latest (unstable) versions of Angular introduce a hook for you to drop in a comparator function, which is where I'd LIKE to put what I'm about to show you. But, I'm stuck on v1.0.7, so I had to approach it with the below.
The issue is that even though the user selects an empty string when they select the "empty" option, the property on the object you're filtering against still exists, so Angular's $filter compares each elements' matching property to that empty string, instead of treating that property as removed.
So, I added an ng-change event on my <select /> directive which would delete the property from my filter template object, thereby resetting the filter. Been working for me so far!
Example:
<!-- Assuming select1 is the filter template object, note the ng-change attribute added to your select element -->
<select ng-change="checkForClear( select1 )" ng-model="select1.name" ng-options="item.name as item.name for item in items" >
<option value="">No filter</option>
</select>
<div ng-repeat="item in items | filter:select1">
{{ item.name }}: {{ item.fruit }}
</div>
<!-- Then, in your controller -->
<script>
// Assuming your controller is set up...
$scope.checkForClear = function( filterTemplate ){
if( filterTemplate.name == null || filterTemplate.name === '' ){
delete filterTemplate.name; // <== THIS removes the property from the template filter and clears the filter for Angular
}
}
</script>
The accepted answer will not work for situations where you need more than one select filter and will only work in a global way like any.
There is some quirky behaviour when you use ng-options with explicit options. I find that falling back
to the simple ng-repeat will work better in some situations.
Instead you should do:
<select ng-model="select1.name">
<option value="" selected>No filter</option>
<option ng-repeat="item in items" ng-value="item.name">{{item.name}}</option>
</select>
Try it - I forked your CodePen
This way you could have two select filters selecting off two properties.
<select ng-model="select1.fruit">
<option value="" selected>No filter</option>
<option ng-repeat="item in items" ng-value="item.fruit">{{item.fruit}}</option>
</select>