Reputation: 712
In my AngularJs project I want to disable the backspace key for all views. Here is an easy jQuery solution. Is there any solution for this written in AngularJs?
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input, textarea")) {
e.preventDefault();
}
});
Regards
Upvotes: 2
Views: 5698
Reputation: 14998
If you want to disable the backspace key for the entire website you can use something similar to this (Angularjs : disable tab key default behaviour) and apply the directive to the body document using the $document
.
Something like this:
angular.module('app', []).directive('muteKey', ['$document', function($document) {
return function(scope, element, attrs) {
$document.on("keydown", function(e) {
/*
* you don't need the $(e.target) if you want to
* disable the key press in any place of the project
* and not just for inputs or textareas
*/
if (e.which === 8) {
e.preventDefault();
}
});
};
}]);
<body mute-key>
<!---->
</body>
Upvotes: 1
Reputation: 48968
Use the $document Service
$document.on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input, textarea")) {
e.preventDefault();
}
});
The $document service has methods which are a subset of jQuery called jqLite.
How can apply this code? My starting app is like
angular.module("my_app", ['ngRoute']);
Put it in a run block:
angular.module("my_app").run(function($document) {
$document.on("keydown", function keydown Handler(e) {
//Put handler code here
});
});
!$(e.target).is("input, textarea")
Can be translated:
(e.target.type == "input") || (e.target.type == "textarea");
Upvotes: 1
Reputation: 2706
You can add an ng-keydown
attribute to your <input
> tag:
<input type="text" ng-keydown="checkKey($event)"/>
$scope.checkKey(keyEvent) {
if (keyEvent.which === 13) {
$event.preventDefault();
}
}
Upvotes: 4