How to set default angular parameter as last parameter?

I have the following code. I am trying to set the default parameter as the last parameter in the select box. If I hardcode the length in 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> 
+5
source share
4 answers

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

 <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> 

However, you should take a look at the ng-options directive, which is a concrete implementation of ng-repeat behavior, 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> 
+5
source

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

 ng-selected="{{$index==myData.length-1}}" 
+1
source

Try the following:

 <select class="form-control" ng-model="mySelect" ng-options="item for item in myData" ng-init="mySelect = myData[myData.length -1]"> </select> 
+1
source

The whole point of Angular (or other MVVM frameworks) is that you can justify its ViewModel conditions and associate the View View with it.

This means that if you need to select something or some preset <input type="checkbox"> , just assign the desired ViewModel state.

In your case, assign mySelect to what you need so that the default ViewModel is assigned. And a presentation will follow.

 $scope.myData = ['a','b','c']; $scope.mySelect = $scope.myData[$scope.myData.length - 1]; // last value 
 <select ng-model="mySelect"> <option ng-repeat="item in myData" value="item">{{item}}</option> </select> 

Not related to the question, but it is better to use ng-options instead of ng-repeat , but the same idea applies:

 <select ng-model="mySelect" ng-options="item for item in myData"> </select> 

Just using ng-selected does not change the underlying model, which is ultimately important in an Angular application.

+1
source

All Articles