Using ng-repeat to generate select options (with Demo)

This is NOT the correct way to use ng-model with a <select> element in AngularJS:

<!-- ERRONEOUS
<select ng-model="vm.areas">
    <option ng-repeat="area in vm.areas"  ng-value="area" id="{{area}}" ng-click="send_index($event, $index)">{{area.name}}
</select>

<input value="{{variable}}">
-->

There is no need to use the ng-click directive. The select directive handles that automatically. The ng-model directive receives or sets the chosen option.

See:


angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };
 }]);
<script src="https://unpkg.com/angular/angular.js"></script>
<div ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

Leave a Comment