AngularJS Catch Enter Keypress Event
Submitted by nurhodelta_17 on Thursday, January 25, 2018 - 09:34.
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.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.- <html ng-app="app">
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);
- }
- });
- <!DOCTYPE html>
- <html ng-app="app">
- <head>
- <meta charset="utf-8">
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body ng-controller="myCtrl">
- <div class="container">
- <div class="col-sm-2 col-sm-offset-5">
- <input type="text" class="form-control" ng-model="myinput" my-enter="alertInput()">
- </div>
- </div>
- <script>
- 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);
- }
- });
- </script>
- </body>
- </html>
Add new comment
- 117 views