使用 AngularJS 时,我应该在 $apply 和 $watch 之间使用哪个?

Which should I use between $apply and $watch when working with AngularJS?

我刚刚开始使用 AngularJS 并开始使用指令。这些很有趣!

我需要实现一个接受 10 个字符的文本区域,应该只接受 a-z A-Z 0-9 $ , ;等..

我建了两个plunk, 一个基于范围触发验证并对文本执行 $watch 另一个我在按键事件上触发验证。我正在使用 element.on('keyup') 事件而不是 ng-keyup。

所以问题是哪种方法更好,为什么这样?我真的很感激一个深思熟虑的答案:-)

这是我为您的评论所做的贡献

1.http://plnkr.co/edit/5n8HBGVDnLcYcSI8DrbP

var ValidatorDirective = function() {
return {
  restrict: 'A',
  link: function(scope, element, attributes, controller) {
    scope.charsleft = attributes.allowedlength;
    scope.$watch('text', function(newVal, oldVal, scope) {
      TextAreaWatcher(newVal, oldVal, scope, attributes);
    });

2.http://plnkr.co/edit/WCosbgFeQ6Ow8p2YI4q0

var ValidatorDirective = function() {


return {
  restrict: 'A',
  compile: function(element, attributes) {
    attributes.$set('ng-trim', false);
    return function(scope, element, attributes, controller) {
      var maxAllowedLength = Number(attributes.allowedlength);
      var localModel = scope.data;
      localModel.charsleft = maxAllowedLength;
      element.on('keyup', function(keyEvent) {
        scope.$apply(function() {
          var newVal = element.val();
          TextAreaWatcher(newVal, localModel, attributes);
        });
      });
    }
  },
  scope: {
    data: '=data'
  }
}

}

干杯!

这是非常不同的

$watch 有助于监听 $scope 的变化,这意味着 它会针对模型或表达式中的每个变化(例如:- keyup,控制器中的赋值等)触发

element.on('keyup', function(keyEvent) 是一个 jquery 事件,因此您需要通过 $apply tutorial. [=12= 手动应用摘要循环]

$apply enables to integrate changes with the digest cycle

因此,第一个在捕获所有更改方面效率更高(但它会进行脏检查,如果您针对单一类型的更改进行检查,成本可能更高。)