带有 `this` 的指令不给出当前元素 angular js

directive with `this` doesnt give current element angular js

我在 angular js 中使用此指令来跟踪输入按键

angular.module('botApp').directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});

但是当我在输入元素(位于 ng-repeat 内)上尝试此操作时

<input id="inp-test_text" class="default-input inp-loading" type="text" 
       name="test_text" ng-model="app.test_text"
       my-enter="inputEnter(this)">

在 js 中我有:

   $scope.inputEnter = function(currentInput) {
        console.log(currentInput);
    }

我得到这个作为答案:

所以我得到了除了当前输入信息之外的所有信息。如何获取我按下 enter 的元素? ($event, $element 不能作为参数)

Angular expressions , the identifier this accesses the context object which in the case of $eval 中是 scope 对象。

要提供本地element,添加为本地:

app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    ̶s̶c̶o̶p̶e̶.̶$̶e̶v̶a̶l̶(̶a̶t̶t̶r̶s̶.̶m̶y̶E̶n̶t̶e̶r̶)̶;̶
                    scope.$eval(attrs.myEnter, {$element: element});
                });

                event.preventDefault();
            }
        });
    };
});

然后它将作为本地可用:

<input id="inp-test_text" class="default-input inp-loading" type="text" 
       name="test_text" ng-model="app.test_text"
       ̶m̶y̶-̶e̶n̶t̶e̶r̶=̶"̶i̶n̶p̶u̶t̶E̶n̶t̶e̶r̶(̶t̶h̶i̶s̶)̶"̶
       my-enter="inputEnter($element)">

有关详细信息,请参阅