1

I have a directive that, when enter is pressed, an event or expression is fired. I want to pass the element value to the event or expression as seen by my attempt: { 'myArg': element.val() }

The directive works and my event is called, but the parameter is undefined.

What am I missing or what do I need to fix?

app.directive('schdKeyenter', function () {
  return function (scope, element, attrs) {
    element.bind("keydown keypress", function (event) {
        if (event.which === 13) {

            scope.$apply(function () {
                scope.$eval(attrs.schdKeyenter, { 'someArg': element.val() });
            });

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

Usage:

<input type="text" schd-keyenter="onEnterPressed(someArg)">

When onEnterPressed() is called, someArg is undefined.

scniro
  • 16,844
  • 8
  • 62
  • 106
Steve Kinyon
  • 805
  • 1
  • 7
  • 15

1 Answers1

0

After a few days of looking, I finally found an example that cleared the way. I didn't know about the $parse, which makes it all possible. There might be another way to do this but for now this is my solution.

app.directive('schdKeyenter', ['$parse', function ($parse) {

  return function (scope, element, attr) {

    element.bind("keydown keypress", function (event) {
        if (event.which === 13) {

            var attrHandler = $parse(attr['schdKeyenter'])

            scope.$apply(function () {
                attrHandler(scope, { $event: event, $value: element.val() });
            });

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

Usage:

<input type="text" schd-keyenter="onEnterPressed($event, $value)">

The example that I built this from was here: https://stackoverflow.com/a/26591042/3701159.

Community
  • 1
  • 1
Steve Kinyon
  • 805
  • 1
  • 7
  • 15