In this article I will explain with example, how to use AngularJS to get selected Text and Value of HTML Select DropDownList using ng-change directive.
AngularJS: Get selected Text and Value of HTML Select DropDownList using ng-change
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML Select DropDownList which will be populated from JSON array using ng-options directive.
The HTML Select DropDownList has been assigned ng-change directive. When an option is selected in HTML Select DropDownList then the GetValue function of the Controller gets called.
Inside the function, first the selected Value is fetched from the ng-model attribute and the selected Text is fetched from the JSON array using jQuery grep function.
Finally the selected Text and Value is displayed using JavaScript alert message box.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];
$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);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select ng-model="ddlFruits" ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
ng-change="GetValue()">
</select>
</div>
</body>
</html>
Screenshot
Demo
Downloads
Download Code