Currently I'm struggeling by setting the default value for a ng-options in angularjs. Can somebody help me?
I get the Options from a resource.
<select id="customer_country" ng-model="customer.country" ng-options="country.name for country in countries" style="width:230px;">
</select>
My current workaround is to set the default like this:
$scope.countries = Country.query(function() {
$scope.customer.country = $scope.countries[0];
});
But I don't think its the best way to do it. I searched the internet but didn't find a good answer. How would you assign the default value?
Currently I need this that it don't has a null value. Also sometimes it won't have a null value and it shouldn't use the value that is in the model to update the model.
Use ng-init to set default value for ng-options . Save this answer.
AngularJS ng-options Directive The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.
ng-repeat creates a new scope for each iteration so will not perform as well as ng-options. For small lists, it will not matter, but larger lists should use ng-options. Apart from that, It provides lot of flexibility in specifying iterator and offers performance benefits over ng-repeat.
The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.
I encountered the same problem myself, and I believe that's the best way to go about it. That's also the way it's done in their documentation for the ng-options directive.
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