farzad
farzad

Reputation: 654

how can access selected option value in function by AngularJs

I want function get access selected option value by angularJs but not when select tag change or trigger event .

I Use this code when option change.

<select name='type' class='form-control' data-ng-model='type' data-ng-change='change(type)'>
<option value='asc' selected>asc</option>
<option value='desc'>desc</option>
</select>

var app = angular.module('app', []);

app.controller('ctrl', function($scope){
  alert($scope.type);
});

Upvotes: 0

Views: 65

Answers (2)

Alok
Alok

Reputation: 1310

There are many ways of doing what you have asked. To start with if you want to set the default selected item then set it from the controller as I have done in the example below. So that later when you bind the select to something else then it will be rather simple for you ie. you won't have to change any code.

var app = angular.module('app', []);

app.controller('ctrl', function($scope){
  $scope.type = 'asc';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <body ng-app="app" ng-controller="ctrl">
   
   <select name='type' class='form-control' data-ng-model='type'>
    <option value='asc'>asc</option>
    <option value='desc'>desc</option>
  </select>
    
    <p>My Selected type: {{type}}</p>
  </body>

Upvotes: 1

miqe
miqe

Reputation: 3369

Unless you set the default value all you get is null when you do something like console.log($scope.type); but the proper way is to initialize your model with the default value like $scope.type='asc'; first in your controller then you can access the default value whenever you want.

UPDATE: take a look at this Plunker

Upvotes: 2

Related Questions