繁体   English   中英

从api获取选项时如何在angular js中选择选项

[英]How to select an option in angular js when options are fetched from an api

我有一个连接了状态,城市之类的选择框的应用程序。 现在我必须从控制器中输入州名和城市名。 我找不到办法。

<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;

提前致谢。

为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>

另外,可以通过使用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>

工作柱塞链接

对于选择下拉菜单的不同方式,请点击此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM