Tuesday, April 19, 2016

ngOptions that works - Populating select boxes using AngularJS

A quick post explaining how to populate select box using AngularJS with the values that you really want, I’ve found that the way to achieve that is not too obvious in the official documentation for ngOptions.


Let’s assume that you’ve got your data from the server or whatever, it’s a JSON array that looks like this

items = [
          {“itemId”:1, “itemName”:”Item 1”},
          {“itemId”:2, “itemName”:”Item 2”}
        ];


You can populate the values by using this syntax

<select ng-options="item.itemId as item.itemName for item in items">
  <option value="">Choose an item</option>
</select>


This way the value will be the “itemId” and “itemName” is the displayed name.

The empty option is used as a placeholder.

That’s it.

No comments:

Post a Comment