简体   繁体   中英

how to access the value attribute of a select tag in angularjs

I want to get the value attribute of the options of the select... here is my html

<select ng-model = "selectedElement">
 <option vlaue = "1">john</option>
 <option vlaue = "2">harry</option>
 <option vlaue = "3">peter</option>
</select>

when I run the code

console.log($scope.selectedElement);

I got the result "john" in console but what I expected is to get the value attribute. for eg "1" in console. is there any way to do that.

You are using vlaue in the option which is incorrect. Use value that will set the value of each option and gives you that value on $scope.selectedElement

 var app = angular.module('myApp', []); app.controller('MainCtrl', ['$scope', function($scope) { }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MainCtrl"> <select ng-model="selectedElement"> <option value="1">john</option> <option value="2">harry</option> <option value="3">peter</option> </select> selected value is {{selectedElement}} </div> 

You should try this code as well. Define your select box data as an array.

$scope.Fruits = [{
            Id: 1,
            Name: 'Apple'
        }, {
            Id: 2,
            Name: 'Mango'
        }, {
            Id: 3,
            Name: 'Orange'
        }];

Then define a function in your controller page.

      $scope.GetValue = function (fruit) {
            var fruitId = $scope.ddlFruits;
            var fruitName = $.grep($scope.Fruits, function (fruit) {
                return fruit.Id == fruitId;
            })[0].Name;
            $window.alert("Selected Value: " + fruitId + "\nSelected Text: " + fruitName);
        }

And last add the select tag in your html.

       <select ng-model="ddlFruits" ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
        ng-change="GetValue()">
    </select>

Try with this code.Hope this will fix your issue.

<select ng-model="cart.fruit" ng-options="state as state.name for state in shelf"></select>
<br/>
<tt>Cost & Fruit selected: {{cart.fruit}}</tt>

Try above code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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