Search code examples
angularjskeypressangular-directive

directive with `this` doesnt give current element angular js


I'm using this directive in angular js to track an enter keypress

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

but when I try this on an input element (which is inside an 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)">

and in js I have:

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

I get this as an answer:

console-log of currentInput

So I get everything except the current input information. How do I get the element of which I pressed enter on? ($event, $element doesn't work as parameters)


Solution

  • In Angular expressions , the identifier this accesses the context object which in the case of $eval is the scope object.

    To provide the local element, add it as a local:

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

    Then it will be available as a local:

    <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)">
    

    For more information, see