0

我有一个textarea带有jquery.nicescroll 插件和 ng-model 的标签。

<textarea id="paper" ng-model="paper"></textarea>

在我的代码中,我$watch在这个 ng-model 变量上应用了 a 。

$scope.$watch("paper", onTextChange);

一切都很好,除了onTextChange不仅在我输入内容时触发,而且当我点击离开 textareaб 以及切换到另一个选项卡时触发。

如何防止它仅在文本更改时触发onTextChange ,这意味着当我输入内容或删除字符时?

带有说明的演示: plunker

4

2 回答 2

2

这是一个修复:

http://plnkr.co/edit/kycmUrthYU38Ukdz0jJG?p=preview

setTimeout( 
function() {
    $scope.$watch("paper", function(newtext, oldtext) {
      if (newtext !== oldtext) {
        onTextChange();
      }
    });
  }, 100)

所以问题是只要 angularjs 告诉应用程序消化,手表就会触发该功能。您所做的是告诉它每次都调用“更改”函数,此时您应该传入一个检查器函数来检查发生的更改。这是关于“观察”,而不是“观察变化” ——函数参数应该看看你是否需要做某事。

额外说明:

AngularJS 为各种元素上的各种事物设置了观察者——这里有更多信息。我相信模糊对应于触发摘要的ng-touched在Angular中默认添加到$scope.$$watchers的内容是什么?什么触发了 $digests?

于 2015-01-19T10:43:37.600 回答
2

It is a bad idea to use setTimeout. Instead, you could use ng-model-options="{ getterSetter: true }" and write a method to get/set the value (Modified get/set Plunk) and handle the text change condition within this method.

于 2015-01-19T11:21:51.173 回答