【问题标题】:Dynamically assign Angular model to input动态地将 Angular 模型分配给输入
【发布时间】:2014-08-28 20:33:11
【问题描述】:

我正在尝试为 Angular 应用程序创建一个迷你电子表格。我想重新创建 一种常见的电子表格功能,允许用户单击电子表格 单元格,然后使用工作表顶部的较大输入更改该单元格的值。 理想情况下,我想将给定单元格的模型即时分配给大型输入 当用户单击其中一个单元格时,但我无法弄清楚如何执行此操作。

有一些更精细的细节需要通过单元格的模糊和焦点来解决。另外,我给出的例子也大大简化了;可以有任意数量的行和列。我的主要问题是:如何动态地将单元格的模型分配给大输入,以便它可以起作用 作为一种对单元格的代理输入?如果这不可能/不切实际,有没有更好的方法来处理这个问题?

这是我目前所拥有的。我什至不知道这是否可能,特别是我在本指令中采用的方法。有什么想法吗?

http://plnkr.co/edit/6tTsilCGSepYyCfbvidp?p=preview

index.html

<table ng-controller="SpreadsheetCtrl" custom-spreadsheet>
  <thead>
    <tr>
      <th colspan="3">
        <input type="text" style="width: 100%" />
      </th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in rows">
      <td>
        <input ng-model="row.A" type="text" />
      </td>
      <td>
        <input ng-model="row.B" type="text" />
      </td>
      <td>
        <input ng-model="row.C" type="text" />
      </td>
    </tr>
  </tbody>
</table>

script.js

var app = angular.module('app', []);

app.controller('SpreadsheetCtrl', function($scope) {
  $scope.rows = [
    {A: 'a', B: 'b', C: 'c'},
    {A: 'a', B: 'b', C: 'c'},
    {A: 'a', B: 'b', C: 'c'}
  ];
}); 

app.directive('customSpreadsheet', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var primary = element.find('thead input');
      element.on('focus', 'tbody input', function () {
        // of course, this won't work! but it shows the (basic) idea
        // of what I'm trying to do
        primary.attr('ng-model', $(this).attr('ng-model'));
      });
    }
  };
})

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    我会抛出指令并使用 ng-click。这是一个有效的PLUNKER

    注意

    <input ng-model="row.A" type="text" ng-click="choose(row, 'A')"/>
    

    <input type="text" ng-model="selected[attr]" style="width: 100%" />
    

    $scope.choose = function(row, attr) {
        $scope.selected = row;
        $scope.attr = attr;
    }
    

    【讨论】:

    • 不错。永远努力做到这一点。
    • 是的,范围很难弄清楚,因此也需要保存 attr。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多