【问题标题】:bind regular custom js event to angular controller function将常规自定义 js 事件绑定到角度控制器功能
【发布时间】:2016-05-26 07:57:02
【问题描述】:

我正在尝试使用 here 中描述的 angular 指令将 angular 函数绑定到常规 js 事件(logedIn 事件)。

指令代码为:

evApp.directive('onlogin', function () {
return {
    restrict: 'A',
    transclude: true,
    scope: {
        'onlogin': '&'
    },
    link:function (scope, element, attr) {
        //Code to detect when element is pulled goes here
        document.addEventListener("logedIn", function (e) {
            scope.$eval(attr.onlogin);
        });
    }
}
});

html标签是:

<div  onlogin="loggedIn()"></div>

它有效,但我没有找到一种方法来传递链接函数中随事件到达的参数“e”。我尝试仅从 html 传递函数处理程序并使用链接函数中的参数调用该函数,但它没有用。 比如:

<div  onlogin="loggedIn"></div>

谢谢,阿米查

【问题讨论】:

  • 你应该添加 scope.$apply 让 Angular 现在它需要触发摘要循环,然后只需调用 scope.onlogin({e: e});

标签: javascript angularjs


【解决方案1】:

你应该添加 scope.$apply 来让 angular 现在它需要触发摘要循环,然后只需调用 scope.onlogin({e: e}) 基本上你可以在处理程序中使用它,就像你使用 $event 一样。

 evApp.directive('onlogin', function () {
return {
    restrict: 'A',
    transclude: true,
    scope: {
        'onlogin': '&'
    },
    link:function (scope, element, attr) {
        //Code to detect when element is pulled goes here
        document.addEventListener("logedIn", function (e) {
            scope.$apply(function () {
             scope.onlogin({e: e})
            });
        });
    }
}
});

【讨论】:

  • 它给我一个错误,attr.onlogin 不是函数
  • 我改变了 attr.onlogin({e:e});到 scope.onlogin({e:e});现在它的工作。谢谢。
  • 是的,你是对的。我在复制粘贴您的代码时犯了错误,它应该是范围。
【解决方案2】:

onlogin函数的调用需要在匿名函数内部才能添加参数,但函数需要存储在匿名函数外部,否则不会触发。

evApp.directive('onlogin', function () {
    return {
       restrict: 'A',
       transclude: true,
       scope: {
         'onlogin': '&'
       },
       link:function (scope, element, attr) {
          //Code to detect when element is pulled goes here
          document.addEventListener("logedIn", function (e) {
             var fn = scope.onlogin();
             scope.$apply(function () {
                  fn(e);
             });
          });
       }
    }
});

【讨论】:

  • 是的,你这样做是对的,我错过了,因为确实复制粘贴了你的代码片段并且你在那里使用了 attr,显然它应该是范围。我的错误在于足够仔细地阅读代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 2016-09-02
  • 2021-08-14
  • 1970-01-01
  • 2016-12-29
  • 2020-01-07
  • 1970-01-01
相关资源
最近更新 更多