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>
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>
I was able to achive this by using ng-selected in the options attributes.
ng-selected="{{$index==myData.length-1}}"
Try this:
<select class="form-control" ng-model="mySelect"
ng-options="item for item in myData" ng-init="mySelect = myData[myData.length -1]">
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With