Roxx
Roxx

Reputation: 3986

angularjs: set selected item in dropdown from database

I have few dropdowns with predefined field. Now i am making ajax call to database and fetch data. Data is coming properly from the database and i can see the array in firebug(network tab).

I want to set this data as selected in dropdown. In textbox it is simple. But i having hard time with dropdowns.

Ajax code below

formApp.controller('getprofile', function($scope,$http){
     $http({
                            url: 'get_profile.php',
                            method: "GET",
                            params: {uid: uid}
                         })
                    .success(function(data) {

                        if (data.success) {

                      $scope.formData.dob = data.dob;
                      $scope.married = data.married;
}

Html code

<input name="dob" id="dob" type="text" class="form-control textbox1" required="required" placeholder="Date of birth(dd-mm-yyyy) " ng-model="formData.dob">
<div class = "errorba" ng-show="dob">{{dob}}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errormarried }">    
        <select id="married" name="married" class="selector form-control" ng-model="formData.married" required="required"> 

          <option value="0" selected="selected" >Maritial Status</option>
          <option value="1" >Single</option>
          <option value="2">Married</option>

        </select>
<span class="errorba" ng-show="errormarried">{{ errormarried }}</span>
</div>

Data from ajax - 1 1 means Single.

Please advise what am i doing wrong.

Upvotes: 0

Views: 895

Answers (1)

nivas
nivas

Reputation: 3186

change $scope.married = data.married; to $scope.formData.married = data.married; in controller since your ng-model and $scope variable in your controller is different.

In worst case you may get error formData as undefined in your controller. so define $scope.formData = {}; before you use assign values to it.

formApp.controller('getprofile', function($scope,$http){
     $http({
                            url: 'get_profile.php',
                            method: "GET",
                            params: {uid: uid}
                         })
                    .success(function(data) {

                        if (data.success) {
                      $scope.formData = {};
                      $scope.formData.dob = data.dob;
                      $scope.formData.married = data.married;
}

Upvotes: 1

Related Questions