Add Angular JS Dependency
First, we need to add Angular JS and in this tutorial, I'm using a CDN for Angular so you need internet connection for it to work. Place this inside the head tag of your html.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
Define our App Name
Next, we need to define our app name using
ng-app. You could place this in html, body or div tag depending on your needs. In this tutorial, I have placed it in html tag.
Define our Controller
Same as app name you can place it in html, body or div tag using
ng-controller but make sure that your app name comes first than your controller or your controller wont be read.
<body ng-controller="myCtrl">
Creating our Textbox
Next step in to create our textbox where we assign our custom directive that we are going to create in our angular js named
my-enter.
<input type="text" class="form-control" ng-model="myinput" my-enter="alertInput()">
Creating our Angular JS Script
Lastly, we create our angular js script which contains our custom directive and our controller.
var app = angular.module('app', []);
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();
}
});
};
});
app.controller('myCtrl', function($scope){
$scope.alertInput = function(){
alert($scope.myinput);
}
});
In here, we created a custom directive that upon
Enter keypress, in our input html, alertInput function is called. In our controller, alertInput function alerts the input of our textbox.
Here's the
Full HTML of this tutorial:
<!DOCTYPE html>
<title>AngularJS Catch Enter Keypress Event
</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <body ng-controller="myCtrl"> <h1 class="page-header text-center">Press enter to alert Input Value
</h1> <div class="col-sm-2 col-sm-offset-5"> <input type="text" class="form-control" ng-model="myinput" my-enter="alertInput()"> var app = angular.module('app', []);
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();
}
});
};
});
app.controller('myCtrl', function($scope){
$scope.alertInput = function(){
alert($scope.myinput);
}
});
That ends this tutorial. Happy Coding :)