Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and ng-options from resource default value

Tags:

angularjs

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.

like image 706
Christian Schmitt Avatar asked Aug 06 '13 11:08

Christian Schmitt


People also ask

How do I set default value in ng-options?

Use ng-init to set default value for ng-options . Save this answer.

What is Ng option AngularJS?

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.

What is difference between ng-repeat and Ng-options?

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.

What is ngInit?

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.


1 Answers

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.

like image 141
OJ Raqueño Avatar answered Oct 25 '22 00:10

OJ Raqueño