简体   繁体   中英

ng-keyup preventDefault() not working

I know it's far from being a best practice, but I really want to understand what's wrong. I wrote the following code in order to distinguish Enter from shift+Enter, and run the "code" I need:

ng-keyup="($event.keyCode == 13 && !$event.shiftKey)
?
  [$event.preventDefault(),
   commentCtrl.edit(comment.id, comment.text),
   comment.edit=false, comment.text]
:
  return"

when I press enter, I still get a \\n added to my text... :(

Help please!~

Write this in your html

 <input type="text"  ng-keypress="restrictInput($event)" />


 $scope.restrictInput=function(e)
   e.prevenDefault();
 }

Aha! You've got the "wrong" directive! I just changed mine from ng-keyup to ng-keypress and now $event.preventDefault() works as expected. Hope this helps. I was scratching my head a long time on that.

ended up writing a directive that prevents it...

(function() {
    'use strict';

angular
    .module('PreventEnterDrc', [])
    .directive('preventEnter', function () {
        return {
            restrict: 'A',
            link: function(scope, element) {
                element.bind('keydown keypress keyup', function (event) {
                    if(event.keyCode == 13 && !event.shiftKey){
                        event.preventDefault();
                    }
                });
            }
        };
    })
;
})();

Have you tried $event.stopImmediatePropagation(); ? That's what worked for me anyways.

Try the following.

ng-keyup="handleKeyup($event);"

in your controller,

$scope.handleKeyup =  function($event) {
//write your logic here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM