【问题标题】:scope.$watch not firing on variable changescope.$watch 不会在变量更改时触发
【发布时间】:2016-03-07 04:15:51
【问题描述】:

我在下面有以下代码的 sn-p。我遇到的问题是,只要 modal.isOpen 的值设置为 true,$watch 语句就不会触发。我试图避免使用 scope.$apply。我在这里做错了什么......

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();

                  }
              ..........
              });

【问题讨论】:

  • 试试$scope.apply()
  • 它有效,但我试图避免使用 scope.apply。有没有不使用 scope.apply 的其他方法?
  • 如果你想更新模型你应该使用 $apply

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-watch


【解决方案1】:

您应该注意在提供给$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();
    });
  }
  ..........
});

【讨论】:

  • $timeout 开始 $apply?
  • @user1142130 是的..它以更安全的方式启动摘要周期..我永远不会与已经运行的摘要周期冲突..
  • @sani 谢谢队友..我想我已经帮助了你很多次..&通过帮助学到了很多东西..:)
猜你喜欢
  • 1970-01-01
  • 2014-07-20
  • 2015-02-15
  • 2013-07-21
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
相关资源
最近更新 更多