AngularJS Select

In AngularJS, handling dropdown menus goes beyond standard HTML. While you can use the standard <select> element, AngularJS provides the ng-options directive to power these menus dynamically. This allows you to bind complex data structures to your UI, ensuring that when a user selects an option, your underlying model stays perfectly in sync via two-way data binding.

Developer Tip: While you could use ng-repeat to create <option> tags, ng-options is much more memory-efficient and offers better performance, especially when dealing with large datasets or binding to full objects.

Key Concepts of ng-select in AngularJS

  1. ng-model: This is the source of truth. It stores the currently selected value and updates automatically whenever the user picks a new option.
  2. ng-options: This is the "engine" that builds the list. It iterates over an array or object and generates the <option> elements on the fly.
  3. ng-change: A lifecycle hook that fires a function immediately after a selection is made—perfect for triggering API calls or updating other parts of a form.
  4. Multiple Selection: By adding the multiple attribute, AngularJS converts the model from a single value into an array of selected values.
Best Practice: Always provide a default "placeholder" option (like "Select a Country") with an empty value inside your select tag. This prevents AngularJS from generating a blank <option> when the model is initially undefined.

 

Basic Example of Select Dropdown

Simple Select Example

In this scenario, we have a simple array of strings. This is common for basic configuration settings or static lists like categories.

<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-model="selectedItem" ng-options="item for item in items">
    <option value="">Select an item</option>
  </select>
  <p>Selected Item: {{selectedItem}}</p>
</div>

<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.items = ["Standard Shipping", "Express Shipping", "Overnight"];
  });
</script>
  • ng-model="selectedItem": This variable in your controller will hold the string of the chosen shipping method.
  • ng-options="item for item in items": This tells AngularJS to use each string in the array as both the label (what the user sees) and the value (what the model stores).
Common Mistake: If your ng-model is initialized with a value that doesn't exist in your ng-options list, AngularJS will insert an empty option at the top. Ensure your initial model value matches an item in the list or is set to null.

 

Select with Value and Label

In real-world applications, you rarely deal with simple strings. Usually, you have an array of objects (like a list of Users or Products) where you want to show a "Name" but store an "ID" or the entire object.

Example with Object Binding

<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-model="selectedItem" ng-options="item.name for item in items">
    <option value="">Select a Product</option>
  </select>
  <p>You selected ID: {{selectedItem.id}} ({{selectedItem.name}})</p>
</div>

<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.items = [
      { id: 101, name: "Wireless Mouse", price: 25 },
      { id: 102, name: "Mechanical Keyboard", price: 80 },
      { id: 103, name: "USB-C Hub", price: 45 }
    ];
  });
</script>
  • By using item.name for item in items, you are telling AngularJS: "Display the name property in the dropdown, but when selected, put the entire object into the model." This is incredibly powerful for building detail views.
Watch Out: If you only need a specific ID (e.g., 101) rather than the whole object, change your syntax to: item.id as item.name for item in items.

 

Select with Multiple Options

If you are building a tagging system or a user permissions manager, you might need to allow users to select more than one option at a time.

Example of Multiple Selection

<div ng-app="myApp" ng-controller="myCtrl">
  <label>Select your skills:</label>
  <select ng-model="selectedSkills" ng-options="skill for skill in skills" multiple>
  </select>
  <p>Database storage: {{selectedSkills}}</p>
</div>

<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.skills = ["JavaScript", "AngularJS", "CSS", "HTML5", "Node.js"];
    $scope.selectedSkills = []; // Initialize as an array
  });
</script>
  • multiple: This standard HTML attribute tells AngularJS to treat the model as an array.
  • ng-model="selectedSkills": As you hold Ctrl/Cmd and click items, this array will grow and shrink automatically.

 

Using ng-change with Select

The ng-change directive is used when you need to perform an action immediately after the selection happens—such as calculating a total price or loading "Sub-categories" based on a parent category selection.

Example with ng-change

<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-model="selectedCity" ng-options="city for city in cities" ng-change="updateWeather()">
    <option value="">Choose a City</option>
  </select>
  <div ng-if="weatherReport">
    <h3>Weather for {{selectedCity}}:</h3>
    <p>{{weatherReport}}</p>
  </div>
</div>

<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.cities = ["New York", "London", "Tokyo"];
    
    $scope.updateWeather = function() {
      // In a real app, this would be an API call
      $scope.weatherReport = "Fetching data for " + $scope.selectedCity + "... (Simulated)";
    };
  });
</script>
  • ng-change does not trigger if the model is changed programmatically in the controller; it only triggers on user interaction with the select element.

 

Select with Grouping

For long lists, grouping items (like grouping cities by country) makes the UI much more readable. AngularJS supports this natively within ng-options using the group by syntax.

Example with Grouping

<div ng-app="myApp" ng-controller="myCtrl">
  <label>Select an Item:</label>
  <select ng-model="selectedItem" 
          ng-options="item.name group by item.category for item in items">
    <option value="">Select an item</option>
  </select>
  
  <p>Selected: {{selectedItem.name}}</p>
</div>

<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.items = [
      { name: "Apple", category: "Fruit" },
      { name: "Banana", category: "Fruit" },
      { name: "Carrot", category: "Vegetable" },
      { name: "Broccoli", category: "Vegetable" }
    ];
  });
</script>
  • group by item.category: This automatically wraps related items in <optgroup> tags labeled with the category name. This is much cleaner than manually writing HTML tags.
Developer Tip: Use track by (e.g., track by item.id) at the end of your ng-options expression if your data is being refreshed from a server. This helps AngularJS identify objects by a unique ID rather than by object reference, preventing the select from flickering or resetting unexpectedly.

 

Summary

The ng-options directive is the standard way to handle dropdowns in AngularJS. It offers a clean, declarative syntax for turning arrays and objects into interactive menus. By mastering ng-model for binding, group by for organization, and ng-change for logic, you can build complex, data-driven forms with very little code. Remember to always provide a null/empty default option to keep your UI clean and avoid unexpected empty selections.