Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected value from select box in angularjs

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

<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

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

Select box image

Thanks in advance

like image 853
Sharma Vikram Avatar asked Apr 04 '16 10:04

Sharma Vikram


People also ask

How to get selected Dropdown value in AngularJS?

By using ng-model property in AngularJS we can get dropdownlist selected value and text in ng-change event.

Can I use ngModel for select?

The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.

What is ngInit?

The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.


2 Answers

Use ng-options instead of 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:

$scope.nextpage = function(selectedCity){
    console.log(selectedCity);
}
like image 122
Roy Avatar answered Oct 28 '22 07:10

Roy


Here is the sample code.

Html code

 <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

$scope.nextpage = function(currentCity){
    console.log(currentCity);
}
like image 20
vicky Avatar answered Oct 28 '22 06:10

vicky