I recently came across a helpful post on Stack Overflow about creating an Enter keypress directive.
After following the instructions, here is my JavaScript code that replicates the 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>
However, I encountered a problem. When I enter text in the input box and press 'Enter', it does not trigger the alert()
function as expected. It seems like my directive may not be set up correctly to respond to the keypress event on that element.