AngularJS (1.5.8) - How do I populate a select opt

2019-09-10 23:58发布

I have an AngularJS app that I want to populate a select drop down list from a JSON result.

The controller code gets the json but how do I populate the $scope.states.

My drop down remains empty on the fetch and the res of the page does not render.

$scope.accountAddresses is a JSON container with various data. My concern is only for the shippingState key.

HTML Code

<select name="shippingState" id="shippingState"  ng-model="accountAddresses.shippingState"  class="state form-control" size="1">

Controller JSON Fetch Code

 $http.get( serviceBase + 'Assets/us-states.json').success(function(d){
            $scope.states = d;
      });

I tried ng-repeat="state in $scope.states" but I do not get any data (state abbreviations) in the drop down.

JSON Sample Data

[
    {
        "name": "Alabama",
        "abbreviation": "AL"
    },
    {
        "name": "Alaska",
        "abbreviation": "AK"
    }]

How do I get the population to work like the following html code of options?

 <option value="AK">AK</option>
<option value="AL">AL</option>

EDIT

With the following code

 <select name="shippingState" id="shippingState"  ng-model="accountAddresses.shippingState"  ng-options ="s.abbreviation as s.name for s in states" class="state form-control" size="1">

I get the following, but I need to remove "string:" and label

<option value="string:AL" label="Alabama">Alabama</option>
<option value="string:AK" label="Alaska">Alaska</option>

2条回答
叼着烟拽天下
2楼-- · 2019-09-11 00:09

You should be using ng-options for this.

Depending on what you want to show:

<select ng-options="state as state.name for state in states track by state.abbreviation" ng-model="accountAddresses.shippingState"></select>

查看更多
别忘想泡老子
3楼-- · 2019-09-11 00:26

You can do this using ng-options ,

<select ng-model="selectedItem" ng-options ="s.name  for s in states"></select>

Controller:

  function($scope, $http) {
             $http.get('test.json').then(function (response){
                $scope.states = response.data;
                console.log(response);
        });

DEMO APP

查看更多
登录 后发表回答