1

我做了一个非常基本的plunker,它模仿了文本编辑器发生的事情:我们可以在和编辑它们的内容之间file1切换file2。修改内容会触发changeFile,但我想设置一个debounce.

<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  </head>
  <body ng-controller="contentCtrl">
    <div ng-repeat="file in files track by $index">
        <input class="item" ng-model="file.name" ng-click="goFile(file)" ng-readonly="true" style="border: none; cursor: pointer"/>
    </div>
    <br/>
    <textarea ng-change="changeFile(file)" ng-model="file.body" ng-model-options="{ debounce: 2000 }"></textarea>
    <div id="console">Recorded:<br/></div>
    <script>
      var app = angular.module('plunker', []);
      app.controller('contentCtrl', ['$scope', function ($scope) {
        $scope.files = [{name: "file1", body: "body1"}, {name: "file2", body: "body2"}]
        $scope.file = $scope.files[0]

        $scope.goFile = function (file) {
          $scope.file = file
        }

        $scope.changeFile = function (file) {
          document.getElementById("console").innerHTML += file.body + "<br/>"
        }
      }]);
    </script>
  </body>
</html>

这里的问题是,刚刚修改了一个文件的内容后,如果我们很快切换到另一个文件,修改将不会被考虑在内;它不会显示在控制台中。那不是我想要的。changeFile无论是否debounce完成,我都希望切换到另一个文件会触发。

有谁知道如何修改代码来实现这一点?

4

1 回答 1

1

您可以做的是将 a 更改debounce为 a $timeout,因为问题debounce在于它不会将值应用于范围,直到时间结束。

普朗克

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

app.controller('contentCtrl', ['$scope', '$timeout', function($scope, $timeout) {

  $scope.files = [{
    name: "file1",
    body: "body1"
  }, {
    name: "file2",
    body: "body2"
  }]
  $scope.file = $scope.files[0]

  $scope.goFile = function(file) {
    $scope.file = file
    $scope.selectedItem = file
  }

  $scope.changeFile = function(file, time) {
    if (file.timeout) {
      $timeout.cancel(file.timeout);
    }
    file.timeout = $timeout(function() {
      document.getElementById("console").innerHTML += file.body + "<br/>"
      console.log(file.name + " changed: " + file.body);
    }, time)

  }

}]);
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="contentCtrl">
  <div ng-repeat="file in files track by $index" ng-class="{selected : selectedItem === file}">
    <input class="item" ng-model="file.name" ng-click="goFile(file)" ng-readonly="true" style="border: none; cursor: pointer" />
  </div>
  <br/>
  <textarea ng-change="changeFile(file,2000)" ng-model="file.body"></textarea>
  <div id="console">Recorded:<br/></div>
</body>

</html>

我已经添加了通过您想要去抖动的时间量的功能,以便您可以在$scope.changeFile函数中添加一行,以便在更改文件时立即更新。

于 2017-05-12T13:43:04.717 回答