user6002037
user6002037

Reputation:

Select box angular using ng-repeat or ng-options and removing blank option

I have found lots of answers on here, but very frustatingly I am unable to execute it. Firstly to explain what I have done:

I have created an array with a list of country objects. In the html I am looping through the countries array and adding each value to a select box.

I just wish to show both the UK and the US, however with my code there is also a third option (an empty option).

How can I just have the 2 values in the array? This answer should work, but it is not showing the correct values in the html. Perhaps it is because I have been using ng-repeat, but perhaps I should be using ng-options as this answer would suggest?

Please see my code below.

CONTROLLER

this.countries = [
        {name: "United Kingdom"},
        {name: "United States of America"}
    ];

HTML

<select ng-model="ctrl.country">
     <option ng-repeat="country in ctrl.countries" value="{{country.name}}">{{country.name}}</option>     
</select>

Upvotes: 0

Views: 308

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

To remove empty option you need to assign country for ng-model="ctrl.country" value from controller when load this page to show default selected value.

like:

this.countries = [
        {name: "United Kingdom"},
        {name: "United States of America"}
    ];
this.country = this.countries[0].name; // initially show "United Kingdom"

or need to create an another option with empty value to show as selected

<select ng-model="ctrl.country">
    <option value="">select one</option>// default to show 
     <option ng-repeat="country in ctrl.countries" value="{{country.name}}">{{country.name}}</option>     
</select>

Upvotes: 1

Related Questions