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

前端 未结 2 1234
别那么骄傲
别那么骄傲 2020-11-30 15:27

controller:

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


        
相关标签:
2条回答
  • 2020-11-30 16:03

    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:

    • Using ng-repeat to generate select options
    • Using select with ng-options and setting a default value

    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>

    0 讨论(0)
  • 2020-11-30 16:06

    Try data-ng-value instead of value

    <input data-ng-value="{{variable}}">
    
    0 讨论(0)
提交回复
热议问题