How to build a reusable dropdown component in AngularJS?

Loading

Creating a reusable dropdown component in AngularJS allows for consistent UI design and code reusability across multiple parts of an application.


Step 1: Define the AngularJS App

First, create an AngularJS module and a controller to manage dropdown data.

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

app.controller("MainController", function ($scope) {
$scope.countries = [
{ id: 1, name: "USA" },
{ id: 2, name: "Canada" },
{ id: 3, name: "UK" },
{ id: 4, name: "Germany" }
];

$scope.selectedCountry = null;
});

Explanation:

  • countries: Array of dropdown options.
  • selectedCountry: Holds the selected value.

Step 2: Create the Dropdown Directive

Define a custom directive to make the dropdown reusable.

app.directive("customDropdown", function () {
return {
restrict: "E",
scope: {
options: "=",
selected: "=",
label: "@"
},
template: `
<label>{{ label }}</label>
<select ng-model="selected" ng-options="option as option.name for option in options">
<option value="">-- Select --</option>
</select>
`
};
});

Explanation:

  • restrict: 'E': Used as a custom element.
  • options="=": Binds the dropdown data.
  • selected="=": Binds the selected value.
  • label="@": Allows custom labels.
  • ng-options: Dynamically populates the dropdown.

Step 3: Use the Dropdown Component in HTML

<div ng-app="myApp" ng-controller="MainController">
<custom-dropdown options="countries" selected="selectedCountry" label="Select a Country:"></custom-dropdown>
<p>Selected Country: {{ selectedCountry.name }}</p>
</div>

Now, selecting a country updates selectedCountry.


📌 Enhancements

Add Placeholder: Modify <option> for better UX.
Make it Reusable: Use it in multiple places with different datasets.
Support ng-change: Add an event listener if needed.


Summary

  • Reusable dropdown component for AngularJS.
  • Works dynamically with different datasets.
  • Encapsulates UI logic, improving maintainability.

Leave a Reply

Your email address will not be published. Required fields are marked *