angular.directive.ng:options

Work in Progress This page is currently being revised. It might be incomplete or contain inaccuracies.

Description

Dynamically generate a list of <option> elements for a <select> element using the array obtained by evaluating the ng:options expression.

When an item in the select menu is select, the array element represented by the selected option will be bound to the model identified by the name attribute of the parent select element.

Optionally, a single hard-coded <option> element, with the value set to an empty string, can be nested into the <select> element. This element will then represent null or "not selected" option. See example below for demonstration.

Note: ng:options provides iterator facility for <option> element which must be used instead of ng:repeat. ng:repeat is not suitable for use with <option> element because of the following reasons:

Usage

<select ng:options="comprehension">
   ...
</select>

Parameters

Example

  <script>
  function MyCntrl(){
    this.colors = [
      {name:'black'},
      {name:'white'},
      {name:'red'},
      {name:'blue'},
      {name:'green'}
    ];
    this.color = this.colors[2]; // red
  }
  </script>
  <div ng:controller="MyCntrl">
    <ul>
      <li ng:repeat="color in colors">
        Name: <input name="color.name"/> [<a href ng:click="colors.$remove(color)">X</a>]
      </li>
      <li>
        [<a href ng:click="colors.push({})">add</a>]
      </li>
    </ul>
    <hr/>
    Color (null not allowed):
    <select name="color" ng:options="c.name for c in colors"></select><br/>

    Color (null allowed):
    <select name="color" ng:options="c.name for c in colors">
      <option value="">-- chose color --</option>
    </select><br/>

    Select <a href ng:click="color={name:'not in list'}">bogus</a>. <br/>
    <hr/>
    Currently selected: {{ {selected_color:color}  }}
    <div style="border:solid 1px black;"
         ng:style="{'background-color':color.name}">
       &nbsp;
    </div>
  </div>
   it('should check ng:options', function(){
     expect(binding('color')).toMatch('red');
     select('color').option('0');
     expect(binding('color')).toMatch('black');
     select('color').option('');
     expect(binding('color')).toMatch('null');
   });