blu*_*lla 23 angularjs angularjs-directive
我正在寻找方法将输入内的值限制为4并将4位数值处理到我的控制器.
<input type="number" class="form-control input-lg"
ng-model="search.main" placeholder="enter first 4 digits: 09XX">
{{ search.main | limitTo:4}}
Run Code Online (Sandbox Code Playgroud)
tym*_*eJV 58
总是可以为它做一个指令:
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on("keypress", function(e) {
if (this.value.length == limit) e.preventDefault();
});
}
}
}]);
<input limit-to="4" type="number" class="form-control input-lg" ng-model="search.main" placeholder="enter first 4 digits: 09XX">
Run Code Online (Sandbox Code Playgroud)
Rag*_*dra 14
您可以随时使用ng-minlength,ng-maxlength字符串长度和min, max对数量的限制.试试这个
<input type="number"
name="input"
class="form-control input-lg"
ng-model="search.main"
placeholder="enter first 4 digits: 09XX"
ng-minlength="1"
ng-maxlength="4"
min="1"
max="9999">
Run Code Online (Sandbox Code Playgroud)
我用接受的答案作为启动点,但这就是我提出的.
angular.module('beastTimerApp')
.directive('awLimitLength', function () {
return {
restrict: "A",
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
attrs.$set("ngTrim", "false");
var limitLength = parseInt(attrs.awLimitLength, 10);// console.log(attrs);
scope.$watch(attrs.ngModel, function(newValue) {
if(ngModel.$viewValue.length>limitLength){
ngModel.$setViewValue( ngModel.$viewValue.substring(0, limitLength ) );
ngModel.$render();
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
用法
<input name="name" type="text" ng-model="nameVar" aw-limit-length="10"/>
Run Code Online (Sandbox Code Playgroud)
关键是使用$ setViewValue()和$ render()分别设置和显示更改.这将确保$ viewValue和$ modelValue正确并正确显示.您还希望将ngTrim设置false为阻止用户添加超出限制的空格.这个答案是@ tymeJV的回答和这篇博文的合并... https://justforchangesake.wordpress.com/2015/01/10/useful-angularjs-directives/
它会允许退格和删除.
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on("keydown", function() {
if(event.keyCode > 47 && event.keyCode < 127) {
if (this.value.length == limit)
return false;
}
});
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
小智 8
无需使用AngularJS指令.
只需使用旧的标准html属性 maxlength.
<input type="text" maxlength="30" />
Run Code Online (Sandbox Code Playgroud)
你可以使用这段代码:
<input type="number" class="form-control input-lg"
ng-model="search.main"
ng-keypress="limitKeypress($event,search.main,4)"
placeholder="enter first 4 digits: 09XX">
Run Code Online (Sandbox Code Playgroud)
和AngularJS代码:
$scope.limitKeypress = function ($event, value, maxLength) {
if (value != undefined && value.toString().length >= maxLength) {
$event.preventDefault();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84942 次 |
| 最近记录: |