article

Wednesday, January 12, 2022

AngularJS Keypress Event Enter

AngularJS Keypress Event Enter

angularjs CDN
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

index.html
//index.html
<!DOCTYPE html>
<html ng-app="appkeypress">
<head>
	<meta charset="utf-8">
	<title>AngularJS Keypress Event Enter </title>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
	<div class="container">
		<h1 class="page-header text-center">AngularJS Keypress Event Enter</h1>
		<div class="col-sm-4 col-sm-offset-4">
			<input type="text" class="form-control" ng-model="myinput" my-enter="alertInput()">
		</div>
	</div>
<script>
	var app = angular.module('appkeypress', []);

	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>

Related Post