当从api中获取选项时,如何在角度js中选择一个选项

时间:2017-07-26 10:26:14

标签: javascript angularjs

我有一个应用程序已连接选择框,如州,城市。 现在我必须从控制器提供州名和城市名称。 我无法找到方法。

<label>State</label>
                <select ng-change="cities(state);" class="form-control" ng-model="state" required>
                    <option selected>Select</option>
                    <option  ng-repeat="x in state" value="{{x.State}}">{{x.State}}
                    </option>

                </select>
                <label>City</label>
                <select class="form-control" ng-model="city" ng-change="location(city);" required>
                    <option selected>Select</option>
                    <option  ng-repeat="y in cities" value="{{y.city}}">{{y.city}}
                    </option>
                </select>

我在控制器中尝试了此代码,但无效。

     $scope.state=response.data.State;
     $scope.city=response.date.Cities;

提前致谢。

2 个答案:

答案 0 :(得分:0)

使用不同的名称分配ng-repeat数组:

$scope.states=response.data.State;
 $scope.cities=response.date.Cities;

需要以不同的名称选择ng-model:

<label>State</label>
                <select ng-change="cities(state);" class="form-control" ng-model="state" required>
                    <option selected>Select</option>
                    <option  ng-repeat="x in states" value="{{x.State}}">{{x.State}}
                    </option>

                </select>
                <label>City</label>
                <select class="form-control" ng-model="city" ng-change="location(city);" required>
                    <option selected>Select</option>
                    <option  ng-repeat="y in cities" value="{{y.city}}">{{y.city}}
                    </option>
                </select>

答案 1 :(得分:0)

此外,可以使用 ng-options

来实现

让控制器成为:

app.controller('MainCtrl', function($scope) {
   $scope.States = [
{"Name":"Value 1","ID":1},
{"Name":"Value 2","ID":2},
{"Name":"Value 3","ID":3},
{"Name":"Value 4","ID":4}
];

   $scope.Cities = [
{"Name":"Value 1","ID":1},
{"Name":"Value 2","ID":2},
{"Name":"Value 3","ID":3},
{"Name":"Value 4","ID":4}
];

$scope.selectedState=2; //setting default select
$scope.selectedCity=4;
});

HTML

<body ng-controller="MainCtrl">
    <select ng-options="value.ID as value.Name for value in States" 
    ng-model="selectedState" ></select>
    Selected state is : {{selectedState}}
    <hr>
     <select ng-options="value.ID as value.Name for value in Cities" 
    ng-model="selectedCity" ></select>
    Selected city is : {{selectedCity}}
  </body>

使用Plunker link

有关选择下拉列表的不同方法,请参阅plunker click here