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

老子叫甜甜 提交于 2019-12-17 07:53:21

问题


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.


回答1:


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>



回答2:


Try data-ng-value instead of value

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


来源:https://stackoverflow.com/questions/42794759/using-ng-repeat-to-generate-select-options-with-demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!