In this article I will explain with example, how to use AngularJS to get selected Text and Value of HTML Select DropDownList when Button is clicked using ng-click directive.
AngularJS: Get selected Text and Value of HTML Select DropDownList on Button click using ng-click
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 and a Button. The HTML Select DropDownList is populated from JSON array using ng-options directive.
The Button has been assigned ng-click directive. When the Button is clicked, 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>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</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 () {
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">
</select>
<br />
<br />
<input type="button" value = "Get" ng-click = "GetValue()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads
Download Code