I currently have a select in an angular app :
http://jsfiddle.net/4qKyx/251/
And I'm trying to manage my select depending on the number of result.
HTML
<div ng-controller="MyCtrl">
<select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" >
</select>
</div>
JS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },
{ name: 'Enhancement', value: 'enhancement' }
];
if($scope.typeOptions.length == 1){
$scope.form = {type : $scope.typeOptions[0].value};
}else{
// first option set to "select an option" and null -> won't work with required
}
}
If I have only one element in my typeOptions, i want the only option to be pre-selected. Now if I have more than one element, I want an option saying "Select an option" but which can't be let selected in a required select. Thank you in advance for any help !
Can you try you controller code as like below,
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.form = {};
$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },
{ name: 'Enhancement', value: 'enhancement' }
];
$scope.form.type=($scope.typeOptions.length===1) ? $scope.typeOptions[0].value : '';
}
also updated your jsfiddler
The code you've provided on SO works.
Your issue is only on the fiddler with the line
<option style="display:none" value="">select a type</option>
if you want your "placeholder" inside the select, you can do it like that :
if($scope.typeOptions.length == 1){
$scope.form = {type : $scope.typeOptions[0].value};
}else{
$scope.typeOptions.unshift( { name: 'Select a value', value: '' });
}
you can add option element to your select to be like
<select ng-model="" required
ng-options="option.value for option in typeOptions">
<option value=''>- Please Choose -</option>
</select>
and just do the check in you controller if the options.length equals 1 then set the ng-model the good thing is the required validation still works.
here is jsfiddle
if you removed the comment it show select option
Related
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
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.
i'm really new to AngularJS and i like it very much.
But i'm experiencing a problem trying to initialize a prealoaded dropdown with a specific value.
The dropdown is initialized with values available from JSON array, but when i try to select a default value in this dropdown, i don't see that value selected but the ng-model variable is set correctly.
I created a plunker example here http://plnkr.co/edit/7su3Etr1JNYEz324CMy7?p=preview tryng to achieve what i want, but i can't get it to work. I tried with ng-repeat and ng-select, with no luck. Another try i did (in this example) is trying to set the ng-selected property.
This is a part of my html
<body ng-controller="MySampleController">
<select name="repeatSelect" id="repeatSelect" ng-model="SelectedStatus" ng-init="SelectedStatus">
<option ng-repeat="option in StatusList[0]" value="{{option.key}}" ng-selected="{{option.key==SelectedStatus}}">{{option.name}}</option>
</select>
<select name="repeatSelect" id="repeatSelect" ng-model="SelectedOrigin">
<option ng-repeat="option in OriginList[0]" value="{{option.key}}" ng-selected="{{option.key == SelectedOrigin}}">{{option.key}} - {{option.name}}</option>
</select>
<pre>Selected Value For Status: {{SelectedStatus}}</pre>
<pre>{{StatusList[0]}}</pre>
<pre>Selected Value For Origin: {{SelectedOrigin}}</pre>
<pre>{{OriginList[0]}}</pre>
</body>
And this is code from my controller
function MySampleController($scope) {
$scope.StatusList = [];
$scope.OriginList = [];
$scope.ServiceCall = {};
$scope.EntityList = [];
$scope.SelectedStatus = -3;
$scope.SelectedOrigin = 1;
var myList = [
{
item: 'Status',
values: [{ key: -3, name: 'Aperto' },
{ key: -1, name: 'Chiuso' }]
},
{
item: 'Origin',
values: [{ key: 1, name: 'Origin1' },
{ key: 2, name: 'Origin2' },
{ key: 3, name: 'Origin3' }]
}
];
$scope.documentsData = myList;
angular.forEach($scope.documentsData, function (value) {
$scope.EntityList.push(value);
switch ($scope.EntityList[0].item) {
case 'Status':
$scope.StatusList.push($scope.EntityList[0].values);
$scope.EntityList = [];
break;
case 'Origin':
$scope.OriginList.push($scope.EntityList[0].values);
$scope.EntityList = [];
break;
}
});
}
Any help would be appreciated!
Thanks in advance.
You can at least use ng-options instead of ng-repeat + option, in which case the default value works just fine.
<select name="repeatSelect" id="repeatSelect"
ng-options="opt.key as opt.key+'-'+opt.name for opt in StatusList[0]"
ng-model="SelectedStatus"></select>`
You can also make it a bit more readable by specifying the option label as a scope function.
HTML: ng-options="opt.key as getOptionLabel(opt) for opt in StatusList[0]"
Controller:
$scope.getOptionLabel = function(option) {
return option.key + " - " + option.name;
}
Plunker: http://plnkr.co/edit/7BcAuzX5JV7lCQh772oo?p=preview
Value of a select directive used without ngOptions is always a string.
Set as following and it would work
$scope.SelectedStatus = '-3';
$scope.SelectedOrigin = '1';
Read answer here in details ng-selected does not work with ng-repeat to set default value
I have object product = {id: "759", name: "someName", category_id: "139", cartridge_type: 2 ...} in my angular controller.
Why preselected option in ngOptions doesn't work? Select renders empty option as if product.cartridge_type would be null.
HTML
<select class="form-control"
id="cartridge_type"
name="cartridge_type"
ng-init="product.cartridge_type=product.cartridge_type||cartridgeTypeScope[0]"
ng-model="product.cartridge_type"
ng-options="cartridge_type.id as cartridge_type.name for cartridge_type in cartridgeTypeScope">
<option value="">Select type</option>
</select>
JS
$http.get('someApiPath').success(function(data) {
$scope.product = data[0];
console.log( $scope.product );
});
$scope.cartridgeTypeScope = [
{
id: 0,
name : '-'
},
{
id: 1,
name : 'cartridgeType1'
},
{
id: 2,
name : 'cartridgeType2'
}
]
Just simple use cartridgeTypeScope[0].id in ng-init
ng-init="product.cartridge_type=product.cartridge_type||cartridgeTypeScope[0].id"
Thing is that you are using cartridge_type.id as cartridge_type.name which is expecting id in the select but in ng-init you are providing it complete object (cartridgeTypeScope[0]).
So it is not selecting your option value.
Alternatively you can do
You can use same ng-init but remove cartridge_type.id as from your ng-options
ng-init="product.cartridge_type=product.cartridge_type||cartridgeTypeScope[0]"
ng-options="cartridge_type.name for cartridge_type in cartridgeTypeScope"
Hope It help :)
UPDATE
For controller default option you need to do
$scope.product={
"cartridge_type":2
}
UPADTE 2:-
For $http:-
Plunker
I have a select box which is populated with some data from my controller. When an input value changes the contents of the select box should be filtered and a default value should be assigned based on the is default property of the data object.
Is there any way this can be done using angular directives or would it need to be done as a custom filter function doing something along the lines of
angular.forEach(vm.data,function(item){
if (vm.q == item.someId && item.isDefault) {
vm.result = item.value;
}
});
My html looks something like
<div ng-app="myApp" ng-controller="ctrl as vm">
<input type="text" ng-model="vm.q">
<select ng-options="item.value as item.description for item in vm.data | filter:{someId:vm.q}" ng-model="vm.result"></select>
</div>
and my controller looks like:
(function(){
angular.module('myApp',[]);
angular
.module('myApp')
.controller('ctrl',ctrl);
function ctrl()
{
var vm = this;
vm.data = [
{
someId: '1',
description: 'test1',
value: 100,
isDefault: true
},
{
someId: '2',
description: 'test2',
value: 200,
isDefault: false
},
{
someId: '3',
description: 'test3',
value: 100,
isDefault: true
},
];
}
})();
See my plunkr demo here: http://plnkr.co/edit/RDhQWQcHFMQJvwOyHI4r?p=preview
Desired behaviour:
1) Enter 1 into text box
2) List should be filtered to 2 items
3) Select box should pre-select item 1 based on property isDefault set to true
Thanks in advance
I'd suggest you include some 3rd party library, like lodash, into your project to make working with arrays/collections that much easier.
After that you could add ng-change directive for your input.
<input type="text" ng-model="vm.q" ng-change="vm.onChange(vm.q)">
And the actual onChange function in the controller
vm.onChange = function(id) {
var item = _.findWhere(vm.data, { someId: id, isDefault: true });
vm.result = item ? item.value : null;
};
And there you have it.