范围$注意不要对可变变化开火

scope.$watch not firing on variable change

本文关键字:变化 开火 范围      更新时间:2023-09-26

下面有以下代码片段。我遇到的问题是,每当modal.isOpen的值设置为true时,$watch语句都不会触发。我尽量避免使用scope$申请我在这里做错了什么。。。

Angular指令中的内部链接函数:

              link: function (scope, elem, attrs) {
              scope.$watch('modal.isOpen', function(newValue, oldValue) {
                  if (newValue)
                      console.log("This does not trigger...");
              }, true);
              $document.bind('keydown', function (e) {
                  if(e.keyCode >= 48 && e.keyCode <= 90) {
                      scope.modal.isOpen = true;
                      elem.find('input')[0].focus();
                  }
              ..........
              });

您应该监视在给$watch函数的字符串中不应该有scope的属性。

scope.$watch('modal.isOpen', function(newValue, oldValue) {

从自定义事件修改scope时,不会更新绑定。您需要使用$timeout/$apply()启动摘要循环来更新绑定。(如果任何代码在angular上下文之外运行,angular就不会运行摘要循环来更新绑定)。

$document.bind('keydown', function(e) {
  if (e.keyCode >= 48 && e.keyCode <= 90) {
    $timeout(function() {
      scope.modal.isOpen = true;
      elem.find('input')[0].focus();
    });
  }
  ..........
});