【问题标题】:Using ng-repeat to generate select options (with Demo)使用 ng-repeat 生成选择选项(附 Demo)
【发布时间】:2017-08-05 07:21:19
【问题描述】:

控制器:

$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)

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

【问题讨论】:

  • 试试这个 {{Array[val]}}。
  • vm.area[val].name
  • 没有用,继续显示 (vm.area[0].name) 作为字符串

标签: angularjs angularjs-ng-repeat angular-ngmodel


【解决方案1】:

尝试data-ng-value 而不是value

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

【讨论】:

    【解决方案2】:

    不是在 AngularJS 中使用 ng-model&lt;select&gt; 元素的正确方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多