Search code examples
angularjsangularjs-ng-repeatangular-ngmodel

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


controller:

$scope.send_index = function(event, val){ 
    console.log(val);
    $scope.variable = 'vm.areas['+val+'].name';
    console.log( $scope.variable ); 
};

and this is in the view:

<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}}">

where "vm" is my model.


Expression inside of an expression (Angular)

my problem is that i need to have an {{array[]}}, with the index as another expression,

e.g: {{Array[{{val}}]}}.

Already tryed this:

 $scope.variable = ''+'vm.areas['+val+'].name'+'';

The problem is in the view, "variable" is shown like an string

(vm.areas[0].name)

and it donst get the valor of that query.


Solution

  • 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>