【问题标题】:Use ng-Model dynamically based on preset variable根据预设变量动态使用 ng-Model
【发布时间】:2019-06-13 12:16:59
【问题描述】:

所以我有以下错误:

鉴于我有以下模型:

Item {
  key: string,
  name: string,
  data: {
    sectionA: string,
    sectionB: string,
    ...
    sectionZ: string
  }
}

我想通过循环动态绑定基于数组 [A-Z] 的输入文本

房间 = ["A", "B", ... , "Z"]

<div
        class="item"
        ng-repeat="room in rooms"
      >

    <input type="text"
           name="{{ item.key }}"
           class="form-control"
           ng-model="item.data.section"+ room >
</div>

似乎当我循环时,我从咖啡脚本中收到关于模型无效的错误,所以我的问题是如何为模型设置正确的值。

【问题讨论】:

    标签: angularjs coffeescript


    【解决方案1】:

    如果您使用item.data.section,那么这将变成undefined,因为您的对象中没有名为section 的键,然后ng-model 将是undefined + room,从而导致undefined .

    您可以使用ng-model="item.data['section' + room]" 来引用您的密钥。您在下面有一个工作示例。我添加了一个更新函数,以查看ng-model 绑定确实有效。

    var module = angular.module("myModule", []);
    module.controller("myController", function($scope) {
      $scope.item = {
        key: "itemKey",
        name: "itemName",
        data: {
          sectionA: "section A String ",
          sectionB: "section B String ",
          sectionZ: "section Z String "
        }
      };
    
      $scope.rooms = ['A', 'B', 'Z'];
    
      let i = 0;
      $scope.updateValues = function() {
        setInterval(function() {
          Object.keys($scope.item.data).forEach(key => {
            let v = $scope.item.data[key];
            v = v.substr(0, v.length - 1) + i;
    
            $scope.item.data[key] = v;
            i = (++i) % 10;
          });
    
          setTimeout(function() {
            $scope.$apply()
          }, 0);
        }, 1000);
      }
    
      $scope.updateValues();
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <div ng-app="myModule">
      <div ng-controller="myController">
        <div class="item" ng-repeat="room in rooms">
          {{ room }}
          <input type="text" name="{{ item.key }}" class="form-control" ng-model="item.data['section' + room]">
        </div>
      </div>
    </div>

    干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多