Rani Radcliff
Rani Radcliff

Reputation: 5076

Angular Default Value in Server Supplied Dropdownlist

I have a dropdownlist of U.S. States which is populated from a call to our web api. I have an edit page that fills in a user's details and I need to bind that dropdownlist to the state in the user's information. I'm sure this has something to do with ng-options, but I do not know how to implement it.

Here is my HTML for the dropdownlist:

<select data-ng-model="form.vchOfficeStateVchID" ng-options="s as s.StateVchID for s in userdetails.vchOfficeStateVchID" style="height:25px">
    <option value="">--Select State--</option>
    <option ng-repeat="state in states" value="state.StateVchID">{{state.StateVchID}}</option>
</select>

The function in my controller that populates the dropdownlist is:

getStates();
function getStates() {
    operatorService.getallstates()
    .success(function (data) {
        $scope.states = data;
    });
};

It returns an array which has the state abbreviation as its key "StateVchID" (I didn't create this database).

The user info is returned in the controller with the following function:

$scope.showDetails = function (user) {
    $scope.noUser = false;
    var userid = user.UserID;
    operatorService.getuserdetails(userid)
    .success(function (data) {
        $scope.userdetails = data;
        $scope.form.vchOfficeStateVchID = userdetails.vchOfficeStateVchID;
        $scope.form.vchOfficeCountryVchID = userdetails.vchOfficeCountryVchID;
    });
    $scope.viewUser = true;
};

In the user's details, the State Abbreviation is held in the vchOfficeStateVchID field.

How do I get my dropdownlist to display the user's correct state? Basically, I need state.StateVchID = userdetails.vchOfficeStateVchID.

Any assistance is greatly appreciated!

Upvotes: 0

Views: 58

Answers (1)

Arg0n
Arg0n

Reputation: 8423

Have a look at this example:

HTML

<div ng-app="myApp" ng-controller="myController">
    <select name="vchOfficeStateVchID" ng-model="form.vchOfficeStateVchID" ng-options="s.StateVchID as s.Name for s in states">
      <option value="">--Select State--</option>
    </select>
    <br/>
    <div>
      <h3>
        Selected ID:
      </h3>
      {{form.vchOfficeStateVchID}}
    </div>
</div>

JavaScript

var app = angular.module("myApp", []);

app.controller("myController", ["$scope", function($scope){
    $scope.userdetails = {
      vchOfficeStateVchID: 3
    }

    $scope.form = {};

    $scope.states = [
      {
        Name: "New York",
        StateVchID: 1
      },
      {
        Name: "Texas",
        StateVchID: 2
      },
      {
        Name: "Las Vegas",
        StateVchID: 3
      },
      {
        Name: "Hawaii",
        StateVchID: 4
      }
    ];

    $scope.form.vchOfficeStateVchID = $scope.userdetails.vchOfficeStateVchID;
}]);

Upvotes: 1

Related Questions