Nizam Ali
Nizam Ali

Reputation: 241

Appending null value in options of select tag using Angular JS

While appending the option values to select tag, an empty option tag is also getting appended using Angular JS. I couldn't figure it out why it adds so. Here is my JS code

    // Create global countries array.
    $scope.countries = [];

    countryPromise.success(function(data, status, headers, config) {
        for(index in data) {
                console.log("ID:"+data[index].id+" Name:"+data[index].name);
            $scope.countries.push({
                id:data[index].id,
                name:data[index].name                   
            });
        }
        $scope.countrylist = $scope.countries;

My HTML

<select ng-model="country" ng-change="changeCountry()" ng-options="v.name for v in countrylist">

Output of console

ID:1 Name:India 

Upvotes: 0

Views: 282

Answers (2)

Brocco
Brocco

Reputation: 65043

If your model (country) is not set to a country then you will not see a selected value initially which will show as blank row when you first open the drop down, but after selecting an item that should go away. This is of course based on the assumption that your array does not have a null value.

Added an example fiddle:

http://jsfiddle.net/65RkM/1/

<select ng-model="country" ng-options="c.name for c in countrylist"></select>

Upvotes: 1

sjdaws
sjdaws

Reputation: 3526

Most likely a blank record is being returned from your database. The simplest solution would be to check index for blanks.

// Create global countries array.
$scope.countries = [];

countryPromise.success(function(data, status, headers, config) {
    for(index in data) {
        if (data[index].id) {
            $scope.countries.push({
                id:data[index].id,
                name:data[index].name                   
            });
        }
    }
    $scope.countrylist = $scope.countries;

Upvotes: 0

Related Questions