2014-12-05 44 views
10

我不希望用户在文本字段中输入空格。我不希望它提交验证,而是 - 一个空格不会显示在文本字段上时,他们点击它。角度限制不允许在文本字段中输入空格

+0

你到目前为止尝试过什么?我建议你编写一个自定义指令,它在keydown上监视keyCode并采取适当的操作。 – 2014-12-05 19:30:48

回答

13
<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text"> 

更新: 要改善代码质量,您可以改为创建自定义指令。但不要忘记,你的指令不仅要防止键盘输入,还要防止粘贴。

<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue"> 

添加ng-trim =“false”属性以禁用输入的修剪非常重要。

angular 
    .module('app') 
    .directive('restrictField', function() { 
    return { 
     restrict: 'AE', 
     scope: { 
      restrictField: '=' 
     }, 
     link: function (scope) { 
      // this will match spaces, tabs, line feeds etc 
      // you can change this regex as you want 
      var regex = /\s/g; 

      scope.$watch('restrictField', function (newValue, oldValue) { 
       if (newValue != oldValue && regex.test(newValue)) { 
       scope.restrictField = newValue.replace(regex, ''); 
       } 
      }); 
     } 
    }; 
    }); 
+0

如果您可以使用简单的replace()代替,为什么使用'split()'后跟'join()'? – PLPeeters 2017-10-31 15:39:32

26

选定的答案可以说是不是很unobtrusive。如果你需要在多个地方使用它,你最终会得到重复的代码。

我更喜欢用下面的指令来防止输入空格。

app.directive('disallowSpaces', function() { 
    return { 
    restrict: 'A', 

    link: function($scope, $element) { 
     $element.bind('input', function() { 
     $(this).val($(this).val().replace(/ /g, '')); 
     }); 
    } 
    }; 
}); 

这个指令可以调用这样的:

<input type="text" disallow-spaces> 
+4

这是比选定的答案更清洁的解决方案。 – GEMI 2016-10-03 09:34:52

+1

如果用户将一个字符串与空格粘贴到输入中会发生什么? – 2016-11-08 20:23:30

+1

@IlyaLuzyanin好问题。我原来的指示可能不会在那种情况下起作用。我用一个指令来代替我的答案,该指令确实占用了粘贴的空间。 – 2016-11-08 21:05:22

2

指令杰森写道:我没有工作。我不得不改变返回false到:e.preventDefault()像这样:

app.directive('disallowSpaces', function() { 
    return { 
     restrict: 'A', 

     link: function($scope, $element) { 
      $element.bind('keydown', function(e) { 
       if (e.which === 32) { 
        e.preventDefault(); 
       } 
      }); 
     } 
    } 
}); 
+0

粘贴文本失败 – 2017-03-10 10:08:23

+0

我明白了。那么这有助于防止特殊字符,也许它适用于禁止空格。粘贴不会在这里工作:http://kopy.io/KNoU1 – Bento 2017-03-10 13:25:51

1

这工作,以防止输入任何特殊字符(包括空格):

app.directive('noSpecialChar', function() { 
return { 
    require: 'ngModel', 
    restrict: 'A', 
    link: function(scope, element, attrs, modelCtrl) { 
     modelCtrl.$parsers.push(function(inputValue) { 
      if (inputValue == null) 
       return '' 
      let cleanInputValue = inputValue.replace(/[^\w]|_/gi, ''); 
      if (cleanInputValue != inputValue) { 
       modelCtrl.$setViewValue(cleanInputValue); 
       modelCtrl.$render(); 
      } 
      return cleanInputValue; 
     }); 
    } 
} 
}); 
0

如果你想实现它,而无需编写指令

ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()"

相关问题