如何使用 AngularJS 限制输入的值? [英] How can you limit the value from input using AngularJS?

查看:23
本文介绍了如何使用 AngularJS 限制输入的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将输入中的值限制为 4 并将 4 位值处理到我的控制器的方法.

I am looking for ways to limit the value inside the input to 4 and process the 4 digit value unto my controller.

 <input type="number" class="form-control input-lg"
 ng-model="search.main" placeholder="enter first 4 digits: 09XX">
                {{ search.main | limitTo:4}}

推荐答案

可以随时为其制定指令:

Can always make a directive for it:

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">

这篇关于如何使用 AngularJS 限制输入的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆