In the previous post, we learnt about working with radio buttons in AngularJS. in this post, we shall learn how to work with HTMl Select element (drop down). In this we are going to learn following
In the below <script> block, we have declared a PersonalDetails as well as People properties (both are JSON collection) of the $scope object. Apart from that we have a SelectedValue property set as "" that will hold the selected value fromt the drop down.
Next, we have declared FullName function that accept an item of the array as parameter returns the combination of FirstName and LastName.
We also have a SearchDetails function that holds the Searched record based on FirstName property of the item into $scope.SearchedDetails.
<script>
var app = angular.module("app", []);
app.controller("SelectController", function ($scope) {
$scope.PersonalDetails = [{ FirstName: 'Sheo', LastName: 'Narayan', active : false },
{ FirstName: 'Sushmita', LastName: 'Narayan', active: true },
{ FirstName: 'Sushant', LastName: 'Shankar' },
{ FirstName: 'Sain', LastName: 'Dogvnta', active: true }];
$scope.People = {
"R": "Ram",
"S": "Shyam",
"M": "Moham",
"G": "Gita",
"L": "Lakhesh",
"J": "John"
};
$scope.SelectedValue = "";
$scope.FullName = function (person) {
return person.FirstName + ' ' + person.LastName;
};
$scope.SearchDetails = function (thisFName) {
$scope.SearchedDetails = { FirstName: thisFName };
};
});
</script>
In the HTML block,
<div ng-app="app" ng-controller="SelectController">
<p>
Default : <select name="select1"
ng-model="SelectedValue" ng-options="details.FirstName for details in PersonalDetails"></select>
</p>
<p>
Default value : <select name="select2" ng-model="SelectedValue" ng-options="details.FirstName for details in PersonalDetails">
<option value="">Please select ...</option>
</select>
</p>
<p>
Group by : <select name="select3" ng-model="SelectedValue"
ng-options="details.FirstName group by details.LastName for details in PersonalDetails">
<option value="">Please select ...</option>
</select>
</p>
<p>
Combine fields: <select name="select4" ng-model="SelectedValue"
ng-options="FullName(details) for details in PersonalDetails">
</select>
</p>
<p>
Full Name alias: <select name="select5" ng-model="SelectedValue"
ng-options="details.FirstName as FullName(details) for details in PersonalDetails"></select>
</p>
<hr />
<p>Selected object : <b>{{ SelectedValue }}</b></p>
<p>Selected name : <b>{{ SelectedValue.FirstName }}</b></p>
<hr />
<h2>Search </h2>
<select id="select6" ng-model="SearchedDetails"
ng-options="details.FirstName for details in PersonalDetails track by details.FirstName">
<option value="">No details</option>
</select><br />
Search based on First name: <input type="text" ng-model="thisFirstName" ng-change="SearchDetails(thisFirstName)" /><br />
<p>Found details : <b>{{ SearchedDetails }}</b></p>
</div>
Output
Views: 18140 | Post Order: 51