在 ng 重复中进行内联编辑时,输入字段会模糊

Input field blurs when inline editing in ng-repeat

本文关键字:编辑 输入 字段 模糊 ng      更新时间:2023-09-26

我正在尝试对数据表进行内联编辑(请参阅plunkr)

<table class="table table-bordered">
<tr ng-repeat="data in dataset" >
  <td ng-repeat="(key, value) in data"  >
    <div class="key-block">
           <strong >{{key}}</strong>
        </div>
        <div class="val-block" inline-edit="data[key]" on-save="updateTodo(value)" on-cancel="cancelEdit(value)">
        <input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
        <button ng-click="cancel()" ng-show="editMode">cancel</button>
        <button ng-click="save()" ng-show="editMode">save</button>
        <span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
            <span ng-hide="editMode" ng-click="edit()">{{model}}</span>
            <a ng-show="showEdit" ng-click="edit()">edit</a>
        </span>
    </div>
  </td>
</tr>

我可以在很多地方看到,我们必须在ng-repeat内部使用ng-model .以避免范围问题。正如我dont know the key already的那样,我正在为模型做data[key]。输入单个字符后,输入字段模糊。

您描述的行为是正常的。如果你仔细观察,你会发现输入值和指令都绑定到同一个对象,即data[key]。当您更改文本输入的值时,model会更新,最终触发指令的刷新,您将返回到"列表"视图。

解决此问题的一种简单解决方案是在指令和输入值之间使用中间变量,并仅在单击保存按钮时更新模型。像这样:

  //Directive
  scope.newValue = null;
  scope.edit = function() {
    scope.editMode = true;
    scope.newValue = scope.model;
    $timeout(function() {
      elm.find('input')[0].focus();
    }, 0, false);
  };
  //Template
  <input type="text" on-enter="save()" on-esc="cancel()" ng-model="newValue" ng-show="editMode">

你可以在这里看到一个修改过的弹跳器。