0

at this point, I'm new to AngularJS.

This works:

scope.$apply(scope.hideTooltip());

But calling the function dynamically does not work:

scope.$apply(
  scope.$eval(attrs.ngEnter, {'event': event})
);

HTML:

<input type="text" ng-model="value" ng-enter="hideToolTip()" />

The enitre directive:

   app.directive('ngEnter', function() {
            return function(scope, element, attrs) {
                console.log(scope.hideTooltip());
                element.bind("keydown keypress", function(event) {
                    if(event.which === 13) {
                        console.log(attrs.ngEnter);
                        scope.$apply(
                            scope.$eval(attrs.ngEnter, {'event': event})
                        );
                        event.preventDefault();
                    }
                });
            };
        });

So, how do I call a function dynamically in an AngularJS directive?

2

1 Answer 1

2

seems like you have missed the argument for the controller method in the HTML

// you have missed the event parameter.

<input type="text" ng-model="value" ng-enter="hideToolTip(event)" />

app.directive('ngEnter', function() {
    return function(scope, element, attrs) {

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

          console.log(attrs.ngEnter);
          scope.$apply(
            scope.$eval(attrs.ngEnter, {
              'event': event
            })
          );
          event.preventDefault();
        }
      });
    };
  });

in controller

 $scope.hideToolTip = function(event) {
    console.log(event);
  }

here is the DEMO

P.S. this will call the controller function twice after hitting ENTER since your binding both keydown and keypressevents.

AND Don't forget to remove the console.log(scope.hideTooltip()); line.

Sign up to request clarification or add additional context in comments.

2 Comments

That's it. Thanks! Yes, I was passing the event parameter but the controller function didn't have any parameters. Strange that it didn't trigger a method undefined exception.
:) glad to help you and additionally if you want to call the console.log(scope.hideTooltip()); the way you have to use here is console.log(scope.hideToolTip);, cheerz :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.