Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a default angular select option as the last option?

Tags:

angularjs

I have the following code. I'm trying to set the default option as the last option in the select box. If I hardcode the length in the ng-init it works. ng-init="mySelect = 3" But not with ng-init="mySelect = myData.length-1"

Any ideas how to set it to the last option?

$scope.myData = ['a','b','c'];

<select class="form-control" ng-init="mySelect = myData.length-1" ng-model="mySelect">
    <option ng-repeat="$index in  myData" value="{{ $index }}" >Select This Option #({{ $index+1 }})</option>
</select>
like image 787
KingKongFrog Avatar asked Sep 13 '15 16:09

KingKongFrog


3 Answers

Using ng-selected and the $index counter we can conditionally set ng-selected="true" for the last option by checking that $index is equal to the last index of your myData array (myData.length - 1). For example:

<option ng-selected="{{$index === myData.length - 1}}"></option>

Or as @wickY26 pointed out, we can also accomplish this using $last:

<option ng-selected="$last"></option>

You should however take a look at the ng-options directive which is a particular implementation of the ng-repeat behaviour but for <select> elements:

<select 
    class="form-control"
    ng-init="mySelect = myData[myData.length - 1]"
    ng-model="mySelect"
    ng-options="data for data in myData">
</select>
like image 94
sdgluck Avatar answered Nov 15 '22 10:11

sdgluck


I was able to achive this by using ng-selected in the options attributes.

ng-selected="{{$index==myData.length-1}}" 
like image 31
KingKongFrog Avatar answered Nov 15 '22 12:11

KingKongFrog


Try this:

<select class="form-control" ng-model="mySelect" 
 ng-options="item for item in  myData" ng-init="mySelect = myData[myData.length -1]">
</select>
like image 28
Diana R Avatar answered Nov 15 '22 11:11

Diana R