Setting null values with an HTML using AngularJS.

In AngularJS, setting null values in select dropdowns requires proper model initialization and template configuration. This approach is useful when you want to handle undefined or empty selections.

Controller Setup

First, define the controller with a null-initialized model and populate the options array:

function display($scope) {
   $scope.obj = {"selected": null};
   $scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}];
}

HTML Template

The template uses ng-options to populate the dropdown and includes a default "Unknown" option:

<div ng-controller="display">
   <select ng-model="obj.selected"
           ng-options="value.id as value.value for value in objects">
      <option value="">Unknown</option>
   </select>
   <br/>
   {{obj}}
</div>

How It Works

The ng-model="obj.selected" binds to the controller's null value. When no option is selected, the empty <option value=""> displays "Unknown". The ng-options directive generates options from the objects array, using id as the value and value as the display text.

Expected Output

Initial display: {"selected": null}
After selecting "Yes": {"selected": 1}
After selecting "No": {"selected": 0}

Key Points

  • Initialize the model property with null to handle empty states
  • Use an empty <option> tag for default placeholder text
  • The ng-options syntax value.id as value.value sets the ID as the model value
  • Data binding automatically updates when the user makes a selection

Conclusion

Setting null values in AngularJS select dropdowns requires proper model initialization and template structure. This approach provides clean handling of empty or undefined selections with user-friendly placeholder text.

Updated on: 2026-03-15T23:18:59+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements