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

标签 javascript angularjs angularjs-directive

我刚刚开始使用 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、 Controller 中的赋值等)发生时触发

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

$apply enables to integrate changes with the digest cycle

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

关于javascript - 使用 AngularJS 时,我应该在 $apply 和 $watch 之间使用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29274129/

相关文章:

javascript - JavaScript 中的数字是不可变的吗?

javascript - 为什么缩进的文本仍然显示在 IE7 中?

angularjs - 有没有一些generator可以生成angular component api文档?

javascript - AngularJS 异步隔离指令不起作用

javascript - 二维游戏 : Collision Detection fails if FPS below 20

javascript - 自定义 jQuery 屏幕键盘

angularjs - 尝试基于常量在 Controller 中动态设置templateUrl

javascript - JS : Dict of arrays combining by AND operation

javascript - Angularjs - 与标准 html 元素同名的自定义指令

javascript - 无法访问指令 Controller 中的 $scope 值