Kin*_*rog 12 angularjs angularjs-directive
我不希望用户在文本字段中输入空格.我不想在提交验证时使用它,而是在单击文本字段时不会显示空格.
Jas*_*ett 30
选择的答案可能不是非常不引人注目的.如果你需要在多个地方使用它,你最终会得到重复的代码.
我更喜欢使用以下指令阻止输入空格.
app.directive('disallowSpaces', function() {
return {
restrict: 'A',
link: function($scope, $element) {
$element.bind('input', function() {
$(this).val($(this).val().replace(/ /g, ''));
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
可以像这样调用该指令:
<input type="text" disallow-spaces>
Run Code Online (Sandbox Code Playgroud)
Qus*_*ion 15
<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text">
Run Code Online (Sandbox Code Playgroud)
更新:为了提高代码质量,您可以创建自定义指令.但是不要忘记你的指令不仅要防止来自键盘的输入,还要防止粘贴.
<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue">
Run Code Online (Sandbox Code Playgroud)
添加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, '');
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28832 次 |
| 最近记录: |