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

2024-03-03

控制器:

$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[]}},索引作为另一个表达式,

例如:{{Array[{{val}}]}}。

已经尝试过这个:

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

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

(vm.areas[0].name)

它没有得到该查询的价值。


This is NOT正确的使用方法ng-model with a <select>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}}">
-->

无需使用ng-click指示。这选择指令 https://docs.angularjs.org/api/ng/directive/select自动处理。这ng-model指令接收或设置所选选项。

See:

  • Using ng-repeat生成select options https://docs.angularjs.org/api/ng/directive/select#using-ngrepeat-to-generate-select-options
  • 使用选择与ng-options并设置默认值 https://docs.angularjs.org/api/ng/directive/select#using-select-with-ngoptions-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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用ng-repeat生成选择选项(附Demo) 的相关文章

随机推荐