ng-keypress ="返回按($ event,' text')"返回不工作

时间:2015-07-09 09:16:09

标签: angularjs

我无法在ng-keypress事件中返回值。想法是防止少数字符被按下。我知道我可以做同样的事情而不通过event.preventdefault()返回true / false。

ng-keypress ="返回按($ event,' text')"不工作

scope.press = function(event)
{
  event = (event) ? event : window.event;
    var charCode = (event.which) ? event.which : event.keyCode;
  if ((charCode > 31 && (charCode < 48 || charCode > 57)) || charCode==8 ) 
   {
        return;
   }
   else 
  { 
    return false;
  }
 }

1 个答案:

答案 0 :(得分:0)

试试这个指令

.directive('preventKey', function ($timeout, Ls) {

return {
    restrict: 'A',
    link: function ($scope, element, attrs, ngModel) {

        element.bind('keydown', function (e, inputs) {

            var code = e.keyCode || e.which;
            var val = element[0].value;

            var current = document.activeElement;
         //Enter all Charcodes u want where u want to prevent keypress
            if (code === 13) {
                e.preventDefault();
                }
        })
    }
  }
}

在你的Html中使用

<input type="text" ng-model="something" preventKey>