【问题标题】:Lose the focus after inserting a letter插入字母后失去焦点
【发布时间】:2017-06-14 18:32:19
【问题描述】:

我编写了一个脚本,它以两种方式表示 json 数据:JSBin

<!DOCTYPE html>
<html>
  <head>
    <script src="https://handsontable.github.io/ngHandsontable/node_modules/angular/angular.js"></script>
  </head>

  <body ng-app="app">
    <div ng-controller="Ctrl">
      GUI:
      <div ng-repeat="item in data">
        <input ng-model="item.val">
      </div>
      <br><br><br>
      Textarea:<br>
      <textarea rows=10 cols=20 ng-model="dataString"></textarea>
    </div>

  <script>
    var app = angular.module('app', []);
    app.controller('Ctrl', ['$scope', '$filter', function($scope, $filter) {
      $scope.data = [{val: "1"}, {val: "2"}];

      $scope.$watch('data', function(data_new) {
        $scope.dataString = $filter('json')(data_new);
      }, true);

      $scope.$watch('dataString', function(dataString_new) {
        $scope.data = JSON.parse(dataString_new);
      }, true);

    }]);
  </script>
  </body>
</html>

因此,修改GUI中的值会改变textarea中的字符串(因为$watch('data');修改textarea中的字符串会改变GUI(因为$watch('dataString'))。

但是,问题是当我们在GUI中更改值时,插入一个字母后我们失去了焦点。

有人知道怎么修改吗?

【问题讨论】:

    标签: angularjs focus lost-focus angularjs-watch


    【解决方案1】:

    所以问题是您正在迭代一个数组 (ng-repeat) 并更改数组的项目。这些项目从 DOM 中移除并插入新项目,因为它们是字符串,因此按值进行比较。这会让你失去焦点。 不过修复起来很简单。只需按索引跟踪,因为对象的顺序相同。

    变化:

    <div ng-repeat="item in data">
    

    收件人:

    <div ng-repeat="item in data track by $index">
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 2022-01-16
      • 2021-02-15
      • 2021-03-31
      • 2011-10-13
      • 2015-03-20
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多