使用 ng-repeat 生成 select 选项(附 Demo)

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

控制器:

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

这是在视图中:

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

其中“vm”是我的模型。


表达式内部的表达式 (Angular)

我的问题是我需要一个{{array[]}},索引作为另一个表达式,

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

已经试过了:

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

问题出在视图中,“变量”显示为字符串

(vm.areas[0].name)

它没有得到那个查询的勇气。

尝试 data-ng-value 而不是 value

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

不是ng-model与AngularJS中的<select>元素一起使用的正确方法:

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

不需要使用ng-click指令。 select directive 会自动处理。 ng-model 指令接收或设置所选选项。

参见:


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>