如何将$ event从custom指令传递给函数?

时间:2022-04-06 22:55:12

This is some directive that i use for detecting enter key

这是我用来检测输入密钥的一些指令

.directive('enterSubmit', function() {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      elem.bind('keydown', function(event) {
        var code = event.keyCode || event.which;
        if (code === 13) {
          if (!event.shiftKey) {
            event.preventDefault();
            scope.$apply(attrs.enterSubmit);
          }
        }
      });
    }
  }
})

I have a function that i wanna get $event as a parameter to it.

我有一个函数,我想得到$ event作为参数。

$scope.test = function(evt){
   var el = angular.element(evt.target);
   console.log(el[0]);
}

But when i use $event as i could in built-in directives

但是当我在内置指令中使用$ event时

<textarea enter-submit="test($event)"></textarea>

It says evt is undefined so how to do it?

它说evt未定义所以如何做到这一点?

1 个解决方案

#1


Change your if to this:

将你的if改为:

if (!event.shiftKey) {
    event.preventDefault();
    var enterSubmitFunction = $parse(attrs['enterSubmit']);                                 
    enterSubmitFunction(scope, { $event: event });
    scope.$apply();
}

You'll need to inject $parse now, and i'm not sure if you need to use scope.$parent in the enterSubmitFunction or just scope. Try both.

你现在需要注入$ parse,我不确定你是否需要在enterSubmitFunction中使用scope。$ parent或者只是使用scope。试试两个。

#1


Change your if to this:

将你的if改为:

if (!event.shiftKey) {
    event.preventDefault();
    var enterSubmitFunction = $parse(attrs['enterSubmit']);                                 
    enterSubmitFunction(scope, { $event: event });
    scope.$apply();
}

You'll need to inject $parse now, and i'm not sure if you need to use scope.$parent in the enterSubmitFunction or just scope. Try both.

你现在需要注入$ parse,我不确定你是否需要在enterSubmitFunction中使用scope。$ parent或者只是使用scope。试试两个。