Nizam Ali
Nizam Ali

Reputation: 241

Get the option value of the select tag on load in Angular JS

Just as we get the value of a select tag in jquery using $(document).read(function(), do we have something similar in Angular JS?

I'm able to get the value after clicking on a DOM element for which I need to pass it as a parameter

    var countryId = $scope.countrySelected;
    alert("country id:"+countryId); 

    // Ajax call for listing States
    var statePromise = $http.get("ListData.php?method=state&countryid="+countryId);
    $scope.states = [];

    statePromise.success(function(data, status, headers, config) {
        for(index in data) {
            if (data[index].id) {
                $scope.states.push({
                    id:data[index].id,
                    name:data[index].name                   
                });                 
            }
        }
        $scope.statelist = $scope.states;
    });
    statePromise.error(function(data, status, headers, config) {
        alert("Loading countries failed!");
    });

HTML

    <tr><td>Country</td><td><select class="country" ng-model="countrySelected">
                    <option ng-repeat="country in countrylist" value="{{country.id}}" ng-selected="country.id">{{country.name}}</option>

But, when I use it on load, it gives undefined, as the whole page data is not yet loaded. How can we overcome here?

Cheers!

Upvotes: 0

Views: 4335

Answers (1)

gkalpak
gkalpak

Reputation: 48211

Without seeing the whole code it is not easy to determine what might be wrong.
In any case, using ngSelected won't change the value of the model attached to the select element. You should set the value of the countrySelected property inside the scope.
(I also suggest you use the ngOptions directive.)

HTML:

<select ng-model="countrySelected" 
        ng-options="country.id as country.name for country in countryList">
</select>

JS:

$scope.countrySelected = $scope.countryList[0].id;
alert('Selected country ID: ' + $scope.countrySelected);

See, also, this short demo.

Upvotes: 1

Related Questions