saperlipopette
saperlipopette

Reputation: 1693

angularjs select depending on number of options in model

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 !

Upvotes: 0

Views: 168

Answers (3)

Abdelrhman Hussien
Abdelrhman Hussien

Reputation: 374

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

Upvotes: 0

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11398

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: '' });
}

Upvotes: 2

Immanuel Kirubaharan
Immanuel Kirubaharan

Reputation: 1104

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

Upvotes: 2

Related Questions