Javascript 如何从angularjs的选择框中获取选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36400048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:00:21  来源:igfitidea点击:

How to get selected value from select box in angularjs

javascriptangularjs

提问by Sharma Vikram

Hello Everyone

大家好

I am trying to get option value from select box on button click but it shows undefined in console .Options value are coming from server

我试图在单击按钮时从选择框中获取选项值,但它在控制台中显示未定义。选项值来自服务器

Here is my html code

这是我的 html 代码

<div class="form-group">
        <label class="control-form" for="cityid">Selct City</label>
        <select type="text" class="form-control" placeholder="City" id="acity" >
            <option value="">--Select City--</option>
            <option ng-repeat="city in cityinfo" ng-value="{{city.id}}"  ng-selected="{{city.id ==cityid}}">{{city.cityname}}</option>
</select>

<button class="btn btn-info prevnext pull-right" ng-click="nextpage()">Next <i class="fa fa-arrow-right"></i></button>

Controller.js file code

Controller.js 文件代码

  $scope.nextpage = function(pageno) {
   console.log($scope.cityinfo);
   }

Select box image

选择框图像

Thanks in advance

提前致谢

回答by Roy

Use ng-optionsinstead of ng-repeat.

使用ng-options代替ng-repeat

Like this:

像这样:

Updated

更新

<select type="text" class="form-control" placeholder="City" id="acity" ng-options="city.id as city.cityname for city in cityinfo track by city.id" ng-model="selectedCity">
    <option value="">--Select City--</option>
</select>
<button class="btn btn-info prevnext pull-right" ng-click="nextpage(selectedCity)">Next <i class="fa fa-arrow-right"></i></button>

JS:

JS:

$scope.nextpage = function(selectedCity){
    console.log(selectedCity);
}

回答by vicky

Here is the sample code.

这是示例代码。

Html code

html代码

 <select type="text" class="form-control" placeholder="City" id="acity" ng-options="city.id as city.cityname for city in cityinfo track by city.id" ng-model="currentCity">
    <option value="">--Select Cities--</option>
</select>
 <button class="btn btn-info prevnext pull-right" ng- 
  click="nextpage(currentCity)">Next <i class="fa fa-arrow-right"></i> 
  </button>

JS function

JS函数

$scope.nextpage = function(currentCity){
    console.log(currentCity);
}