1

I was following this SO Post on creating an Enter keypress directive.

Here is my JS, in which I simulate the same functionality:

JavaScript

var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);
app.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();
        }
     });
  };

});

function callServerWithSong(){
 alert("calling!");
}

HTML

<div id="search" ng-app="myApp" ng-controller="MainCtrl">
   <input type="text" id="search" my-enter="calServerWithSong()">
</div>

The problem is that when I select the input box, type a string and press enter, it doesn't report an error or execute the alert() which tells me that my directive must not be properly set up to fire when I keypress that element.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Thalatta
  • 4,510
  • 10
  • 48
  • 79

1 Answers1

3

You had a typo of method name while passing through a directive attribute. Also the method should be there in $scope of controller.

HTML

<div id="search" ng-app="myApp" ng-controller="MainCtrl">
   <input type="text" id="search" my-enter="callServerWithSong()">
</div>

Code

function callServerWithSong(){
 alert("calling!");
}

$scope.callServerWithSong = callServerWithSong;
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299