angularjs:只允许将数字输入文本框

时间:2013-04-18 19:10:40

标签: javascript ruby-on-rails angularjs numeric

在angularjs中,有任何可用的功能,只允许将数字输入文本框like

23 个答案:

答案 0 :(得分:63)

此代码显示了如何防止输入非数字符号的示例。

angular.module('app').
  directive('onlyDigits', function () {

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue == undefined) return '';
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
});

答案 1 :(得分:42)

HTML

 <input type="text" name="number" only-digits>

//输入123

  .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseInt(digits,10);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
});

//键入:123或123.45

 .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9.]/g, '');

            if (digits.split('.').length > 2) {
              digits = digits.substring(0, digits.length - 1);
            }

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseFloat(digits);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
 });

答案 2 :(得分:37)

我只是在指令中使用了ng-keypress来输入。

HTML:

<input type="text" ng-keypress="filterValue($event)"/>

JS:

$scope.filterValue = function($event){
        if(isNaN(String.fromCharCode($event.keyCode))){
            $event.preventDefault();
        }
};

答案 3 :(得分:25)

此功能正是您所需要的。 http://docs.angularjs.org/api/ng.directive:input.number

修改

您可以将jquery插件包装到指令中。我在这里创建了一个示例:http://jsfiddle.net/anazimok/jTJCF/

HTML:

<div ng-app="myApp">
    <div>
        <input type="text" min="0" max="99" number-mask="" ng-model="message">
            <button ng-click="handleClick()">Broadcast</button>
    </div>

</div>

CSS:

.ng-invalid {
    border: 1px solid red;
}

JS:

// declare a module
var app = angular.module('myApp', []);

app.directive('numberMask', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).numeric();
        }
    }
});

答案 4 :(得分:17)

这是最简单,最快捷的方式,仅允许输入数字。

<input type="text" id="cardno" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>

由于

答案 5 :(得分:7)

以Anton的答案为基础 -

angular.module("app").directive("onlyDigits", function ()
{
    return {
        restrict: 'EA',
        require: '?ngModel',
        scope:{
            allowDecimal: '@',
            allowNegative: '@',
            minNum: '@',
            maxNum: '@'
        },

        link: function (scope, element, attrs, ngModel)
        {
            if (!ngModel) return;
            ngModel.$parsers.unshift(function (inputValue)
            {
                var decimalFound = false;
                var digits = inputValue.split('').filter(function (s,i)
                {
                    var b = (!isNaN(s) && s != ' ');
                    if (!b && attrs.allowDecimal && attrs.allowDecimal == "true")
                    {
                        if (s == "." && decimalFound == false)
                        {
                            decimalFound = true;
                            b = true;
                        }
                    }
                    if (!b && attrs.allowNegative && attrs.allowNegative == "true")
                    {
                        b = (s == '-' && i == 0);
                    }

                    return b;
                }).join('');
                if (attrs.maxNum && !isNaN(attrs.maxNum) && parseFloat(digits) > parseFloat(attrs.maxNum))
                {
                    digits = attrs.maxNum;
                }
                if (attrs.minNum && !isNaN(attrs.minNum) && parseFloat(digits) < parseFloat(attrs.minNum))
                {
                    digits = attrs.minNum;
                }
                ngModel.$viewValue = digits;
                ngModel.$render();

                return digits;
            });
        }
    };
});

答案 6 :(得分:7)

我的解决方案接受复制和粘贴并保存插入符号的位置。它用于产品成本,因此仅允许正十进制值。可以很容易地重构,允许负数或只是整数位。

angular
        .module("client")
        .directive("onlyNumber", function () {
            return {
                restrict: "A",
                link: function (scope, element, attr) {
                    element.bind('input', function () {
                        var position = this.selectionStart - 1;

                        //remove all but number and .
                        var fixed = this.value.replace(/[^0-9\.]/g, '');  
                        if (fixed.charAt(0) === '.')                  //can't start with .
                            fixed = fixed.slice(1);

                        var pos = fixed.indexOf(".") + 1;
                        if (pos >= 0)               //avoid more than one .
                            fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');  

                        if (this.value !== fixed) {
                            this.value = fixed;
                            this.selectionStart = position;
                            this.selectionEnd = position;
                        }
                    });
                }
            };
        });

点击html页面:

<input type="text" class="form-control" only-number ng-model="vm.cost" />

答案 7 :(得分:2)

这是适合我的方法。它位于samnau anwser,但允许使用ENTER提交表单,使用UPDOWN箭头增加和减少数字,版本为DEL,{{ 1}},BACKSPACELEFT,并使用RIGHT导航到字段。请注意,它适用于正整数,例如金额。

HTML:

TAB

ANGULARJS:

<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >

答案 8 :(得分:2)

基于 djsiz 解决方案,包含在指令中。 注意:它不会处理数字,但可以轻松更新

angular
        .module("app")
        .directive("mwInputRestrict", [
            function () {
                return {
                    restrict: "A",
                    link: function (scope, element, attrs) {
                        element.on("keypress", function (event) {
                            if (attrs.mwInputRestrict === "onlynumbers") {
                                // allow only digits to be entered, or backspace and delete keys to be pressed
                                return (event.charCode >= 48 && event.charCode <= 57) ||
                                       (event.keyCode === 8 || event.keyCode === 46);
                            }
                            return true;
                        });
                    }
                }
            }
        ]);

HTML

 <input type="text"
        class="form-control"
        id="inputHeight"
        name="inputHeight"
        placeholder="Height"
        mw-input-restrict="onlynumbers"
        ng-model="ctbtVm.dto.height">

答案 9 :(得分:2)

只需使用HTML5

即可
<input type="number" min="0"/>

答案 10 :(得分:1)

你可以这样做: 使用 ng-pattern 和RegExp&#34; / ^ [0-9] + $ / &#34;这意味着只有整数才有效。

<form novalidate name="form">
    <input type="text" data-ng-model="age" id="age" name="age" ng-pattern="/^[0-9]+$/">
    <span ng-show="form.age.$error.pattern">The value is not a valid integer</span>
</form>

答案 11 :(得分:1)

这很简单易懂。 只需复制粘贴此代码,您的问题就会得到解决。对于更多条件,只需更改模式中的值即可。您的工作将完成。

<input type="text"  pattern="[0-9]{0,}" oninvalid="this.setCustomValidity('Please enter only numeric value. Special character are not allowed.')" oninput="setCustomValidity('')">

答案 12 :(得分:1)

此解决方案仅接受数字,&#39;。&#39;和&#39; - &#39;

这也限制了文本框中的空格条目。我曾使用该指令来实现同样的目标。

请在下面的工作示例中找到解决方案。

http://jsfiddle.net/vfsHX/2697/

HTML:

<form ng-app="myapp" name="myform" novalidate> 
<div ng-controller="Ctrl">
<input name="number" is-number ng-model="wks.number">
<span ng-show="!wks.validity">Value is invalid</span>
</div>

JS:

var $scope;
var app = angular.module('myapp', []);

app.controller('Ctrl', function($scope) {
    $scope.wks =  {number: 1, validity: true}
});

app.directive('isNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {   
        element.bind("keydown keypress", function (event) {
          if(event.which === 32) {
            event.returnValue = false;
            return false;
          }
       }); 
            scope.$watch(attrs.ngModel, function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    //scope.wks.number = oldValue;
                    ngModel.$setViewValue(oldValue);
                                    ngModel.$render();
                }
            });

        }
    };
});

答案 13 :(得分:1)

你可以检查一下 https://github.com/rajesh38/ng-only-number

  1. 在输入时,它仅限输入文本框中的数字和小数点。
  2. 您可以限制小数点前后允许的位数
  3. 如果从文本框中删除小数点,它还会修剪小数点后的数字,例如如果你已经输入123.45然后删除小数点,它也将删除小数点后面的尾随数字并使其成为123.

答案 14 :(得分:0)

我在this

中激怒了jQuery
.directive('numbersCommaOnly', function(){
   return {
     require: 'ngModel',
     link: function (scope, element, attrs, ngModel) {

        element.on('keydown', function(event) {                  
            // Allow: backspace, delete, tab, escape, enter and .
            var array2 = [46, 8, 9, 27, 13, 110, 190]
            if (array2.indexOf(event.which) !== -1 ||
                 // Allow: Ctrl+A
                (event.which == 65 && event.ctrlKey === true) ||
                 // Allow: Ctrl+C
                (event.which == 67 && event.ctrlKey === true) ||
                 // Allow: Ctrl+X
                (event.which == 88 && event.ctrlKey === true) ||
                 // Allow: home, end, left, right
                (event.which >= 35 && event.which <= 39)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
                event.preventDefault();
            }
         });

     }
   };
})

答案 15 :(得分:0)

我有一个类似的问题,最后挂钩和事件

ng-change="changeCount()" 

然后:

self.changeCount = function () {
      if (!self.info.itemcount) {
        self.info.itemcount = 1;
      }
 };

因此,如果插入了无效的号码,则用户默认为1.

答案 16 :(得分:0)

 <input type="text" ng-keypress="checkNumeric($event)"/>
 //inside controller
 $scope.dot = false
 $scope.checkNumeric = function($event){
 if(String.fromCharCode($event.keyCode) == "." && !$scope.dot){
    $scope.dot = true
 }
 else if( isNaN(String.fromCharCode($event.keyCode))){
   $event.preventDefault();
 }

答案 17 :(得分:0)

我知道这是一篇很老的帖子,但 My Mai 的答案很适合我......

angular.module("app").directive("numbersOnly", function() {
  return {
    require: "ngModel",
    restrict: "A",
    link: function(scope, element, attr, ctrl) {
        function inputValue(val) {
            if (val) {
                //transform val to a string so replace works
                var myVal = val.toString();

                //replace any non numeric characters with nothing
                var digits = myVal.replace(/\D/g, "");

                //if anything needs replacing - do it!
                if (digits !== myVal) {
                    ctrl.$setViewValue(digits);
                    ctrl.$render();
                }
                return parseFloat(digits);
            }
            return undefined;
        }
        ctrl.$parsers.push(inputValue);
    }
  };
});

答案 18 :(得分:0)

我已经完成了

的.js

$scope.numberOnly="(^[0-9]+$)";

html的

<input type="text" name="rollNo" ng-model="stud.rollNo" ng-pattern="numberOnly" ng-maxlength="10" maxlength="10" md-maxlength="10" ng-required="true" >

答案 19 :(得分:0)

此答案是对Leopoldo's answer的简化和优化。

在每次按下按键时从输入中触发一个函数,如下所示:

<input type="text" ng-keydown="onlyNumbers($event);"/>

您可以在控制器中以这种方式描述功能

$scope.onlyNumbers = function(event){    
    // 'up': 38,'right':39,'down':40,'left':37,
    // 'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
    // '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
                 46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
                 54:true,55:true,56:true,57:true };

    // if the pressed key is not listed, do not perform any action
    if(!keys[event.keyCode]) { event.preventDefault(); }
}

如果您使用的是Angular 2+,则可以通过以下方式调用此相同的函数:

<input type="text" (keydown)="onlyNumbers($event);"/>

您的Angular 2+函数应如下所示:

onlyNumbers(event) { // the logic here }

答案 20 :(得分:0)

public class SnmpFetcher {

    static byte[] localEngineID = MPv3.createLocalEngineID();

    static{

        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(localEngineID), 0);

        SecurityModels.getInstance().addSecurityModel(usm);
    }

    private Logger logger = Logger.getLogger(SnmpFetcher.class);

    private Target target = null;
    private SnmpAgentConfig snmpAgentConfig = null;
    private TransportMapping<? extends Address> transport = null;
    private Snmp snmp = null;

    long startTime = System.currentTimeMillis();

    public SnmpFetcher(SnmpTarget snmpTarget) {

        target = snmpTarget.getTarget();

        snmpAgentConfig = snmpTarget.getSnmpAgentConfig();
    }

    public void start() throws AgentException {

        try {
            transport = new DefaultUdpTransportMapping();

            snmp = new Snmp(transport);     

            createAuth(snmpAgentConfig, snmp);

            logger.debug("SNMP Agent : " + target.getAddress() + " added security info ");

            transport.listen();

            logger.debug("SNMP Agent : " + target.getAddress() + " UDP transport is listenening ");

        } catch (Exception e) {
            throw new AgentException(e);
        }

    }

    public void stop() throws AgentException {
        if (snmp != null) {
            try {
                snmp.close();
            } catch (IOException e) {
                throw new AgentException(e);
            }
        }
    }

    private void createAuth(SnmpAgentConfig snmpAgentConfig, Snmp snmp) {
        if (snmpAgentConfig instanceof SnmpAgentConfig_v3) {

            SnmpAgentConfig_v3 snmpAgentConfig_v3 = (SnmpAgentConfig_v3) snmpAgentConfig;

            OctetString username = new OctetString(snmpAgentConfig_v3.getUsername());
            OID authProtocol = snmpAgentConfig_v3.getAuthProtocol();
            OctetString authPassword = new OctetString(snmpAgentConfig_v3.getAuthPassword());
            OID privProtocol = null;
            OctetString privPassword = null;

            if (snmpAgentConfig_v3.getPrivProtocol() != null) {
                privProtocol = snmpAgentConfig_v3.getPrivProtocol();
            }

            if (snmpAgentConfig_v3.getPrivPassword() != null) {
                privPassword = new OctetString(snmpAgentConfig_v3.getPrivPassword());
            }

            logger.debug("SNMP Agent : " + target.getAddress() + " localEngineID : " + new OctetString(localEngineID));

            snmp.setLocalEngine(localEngineID, 0, 0);

            UsmUser usmUser = new UsmUser(username, authProtocol, authPassword, privProtocol, privPassword);

            snmp.getUSM().addUser(username, usmUser);

        }
    }

    private DefaultPDUFactory createPDU(int pduType, Target target, SnmpAgentConfig_v3 snmpAgentConfig, String context) {

        SnmpAgentConfig_v3 snmpAgentConfig_v3 = (SnmpAgentConfig_v3) snmpAgentConfig;

        OctetString contextName = null;

        if (context != null) {
            contextName = new OctetString(context);
        } else {
            contextName = new OctetString();
        }

        OctetString contextEngineID = null;

        if (snmpAgentConfig_v3.getContextAgentId() != null) {
            contextEngineID = new OctetString(snmpAgentConfig_v3.getContextAgentId());
        } else {
            contextEngineID = new OctetString();
        }

        return new DefaultPDUFactory(pduType, contextEngineID, contextName);

    }

    private DefaultPDUFactory createPDU(int pduType, Target target) {
        return new DefaultPDUFactory(pduType);
    }

    public Map<String, SNMPValue> doWalk(String oid) throws AgentException {

        logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "WALK" + " is started for OID : " + oid);

        Map<String, SNMPValue> result = new TreeMap<String, SNMPValue>();

        try {

            start();

            DefaultPDUFactory defaultPDUFactory = createPDU(PDU.GETNEXT, target);

            PDU pdu = defaultPDUFactory.createPDU(target);
            pdu.setRequestID(new Integer32(SNMPRequestIdHandler.getNextRequestId()));

            TreeUtils treeUtils = new TreeUtils(snmp, defaultPDUFactory);
            List<TreeEvent> events = treeUtils.getSubtree(target, new OID(oid));

            if (events == null || events.size() == 0) {
                logger.error("SNMP Agent : " + target.getAddress() + " Error: No result returned, table OID [" + oid + "] ");
                return result;
            }

            for (TreeEvent event : events) {
                if (event == null) {
                    continue;
                }
                if (event.isError()) {
                    logger.error("SNMP Agent : " + target.getAddress() + " Error: table OID [" + oid + "]  Error Status : " + event.getErrorMessage());
                    continue;
                }

                VariableBinding[] varBindings = event.getVariableBindings();
                if (varBindings == null || varBindings.length == 0) {
                    continue;
                }
                for (VariableBinding varBinding : varBindings) {
                    if (varBinding == null) {
                        continue;
                    }

                    result.put("." + varBinding.getOid().toString(), new SNMPValue(varBinding));
                }

            }

        } catch (Exception e) {

            long endTime = System.currentTimeMillis();
            long timeToRun = endTime - startTime;
            logger.error("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "WALK" + " is failed for OID : " + oid + " , Execution Time : " + timeToRun);
            throw new AgentException(e);
        } finally {
            stop();
        }

        long endTime = System.currentTimeMillis();
        long timeToRun = endTime - startTime;

        logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "WALK" + " is finished for OID : " + oid + " , Record Count : " + result.size() + ", Execution Time : " + timeToRun);

        return result;
    }

    public Map<String, SNMPValue> doWalk(String oid, String context) throws AgentException {

        logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "WALK" + " is started for OID : " + oid);

        Map<String, SNMPValue> result = new TreeMap<String, SNMPValue>();

        try {

            start();

            DefaultPDUFactory defaultPDUFactory = createPDU(PDU.GETNEXT, target, (SnmpAgentConfig_v3) snmpAgentConfig, context);

            PDU pdu = defaultPDUFactory.createPDU(target);
            pdu.setRequestID(new Integer32(SNMPRequestIdHandler.getNextRequestId()));

            TreeUtils treeUtils = new TreeUtils(snmp, defaultPDUFactory);
            List<TreeEvent> events = treeUtils.getSubtree(target, new OID(oid));

            if (events == null || events.size() == 0) {
                logger.error("SNMP Agent : " + target.getAddress() + " Error: No result returned, table OID [" + oid + "] , Context : " + context);
                return result;
            }

            for (TreeEvent event : events) {
                if (event == null) {
                    continue;
                }
                if (event.isError()) {
                    logger.error("SNMP Agent : " + target.getAddress() + " Error: table OID [" + oid + "] , Context : " + context + " Error Status : " + event.getErrorMessage());
                    continue;
                }

                VariableBinding[] varBindings = event.getVariableBindings();
                if (varBindings == null || varBindings.length == 0) {
                    continue;
                }
                for (VariableBinding varBinding : varBindings) {
                    if (varBinding == null) {
                        continue;
                    }

                    result.put("." + varBinding.getOid().toString(), new SNMPValue(varBinding));
                }

            }

        } catch (Exception e) {

            long endTime = System.currentTimeMillis();
            long timeToRun = endTime - startTime;
            logger.error("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "WALK" + " is failed for OID : " + oid + " , Context : " + context + ", Execution Time : " + timeToRun);
            throw new AgentException(e);
        } finally {
            stop();
        }

        long endTime = System.currentTimeMillis();
        long timeToRun = endTime - startTime;

        logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "WALK" + " is finished for OID : " + oid + " , Context : " + context + ", Record Count : " + result.size() + ", Execution Time : " + timeToRun);

        return result;
    }

    public SNMPValue get(String oid) throws AgentException {

        logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is started for OID : " + oid);

        long startTime = System.currentTimeMillis();

        SNMPValue result = null;

        try {

            start();

            DefaultPDUFactory defaultPDUFactory = createPDU(PDU.GET, target);

            PDU pdu = defaultPDUFactory.createPDU(target);

            pdu.add(new VariableBinding(new OID(oid)));
            pdu.setRequestID(new Integer32(SNMPRequestIdHandler.getNextRequestId()));

            logger.debug("SNMP Agent : " + target.getAddress() + " OID [" + oid + "] , PDU Request Id : " + pdu.getRequestID());

            ResponseEvent response = snmp.send(pdu, target, transport);

            // Process Agent Response
            if (response != null) {
                PDU responsePDU = response.getResponse();


                if (response.getError() != null) {
                    logger.info("SNMP Agent : " + target.getAddress() + " Response Error : " + response.getError());
                    response.getError().printStackTrace();
                }

                if (responsePDU != null) {
                    logger.debug("SNMP Agent : " + target.getAddress() + " OID [" + oid + "] , PDU Response Id : " + responsePDU.getRequestID());

                    int errorStatus = responsePDU.getErrorStatus();
                    int errorIndex = responsePDU.getErrorIndex();
                    String errorStatusText = responsePDU.getErrorStatusText();

                    if (errorStatus == PDU.noError) {
                        if (responsePDU.getVariableBindings() != null && responsePDU.getVariableBindings().size() > 0) {
                            result = new SNMPValue(responsePDU.getVariableBindings().get(0));
                        } else {
                            logger.error("SNMP Agent : " + target.getAddress() + " Error: Empty or null  OID [" + oid + "] ");
                        }
                    } else {
                        logger.error("SNMP Agent : " + target.getAddress() + " Error: Request Failed.  OID [" + oid + "] , Error Status : " + errorStatus);
                        throw new AgentException("SNMP Agent : " + target.getAddress() + " Error: Request Failed.  OID [" + oid + "] , Error Status : " + errorStatus);
                    }
                } else {
                    logger.error("SNMP Agent : " + target.getAddress() + " Error: Response PDU is null  OID [" + oid + "] ");
                    throw new AgentException("SNMP Agent : " + target.getAddress() + " Error: Response PDU is null  OID [" + oid + "] ");
                }
            } else {
                logger.error("SNMP Agent : " + target.getAddress() + " Error: Agent Timeout.  OID [" + oid + "] ");
                throw new AgentException("SNMP Agent : " + target.getAddress() + " Error: Agent Timeout.  OID [" + oid + "] ");
            }

        } catch (IOException e) {
            long endTime = System.currentTimeMillis();
            long timeToRun = endTime - startTime;
            logger.error("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is failed for OID : " + oid + " , Execution Time : " + timeToRun);
            throw new AgentException(e);
        } finally {
            stop();
        }

        long endTime = System.currentTimeMillis();
        long timeToRun = endTime - startTime;

        if (result != null) {
            logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is finished for OID : " + oid + " , Record Count : " + 1 + ", Execution Time : " + timeToRun);
        } else {
            logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is finished for OID : " + oid + " , Record Count : " + 0 + ", Execution Time : " + timeToRun);
        }

        return result;
    }

    public SNMPValue get(String oid, String context) throws AgentException {

        logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is started for OID : " + oid);

        long startTime = System.currentTimeMillis();

        SNMPValue result = null;

        try {

            start();

            DefaultPDUFactory defaultPDUFactory = createPDU(PDU.GET, target, (SnmpAgentConfig_v3) snmpAgentConfig, context);

            PDU pdu = defaultPDUFactory.createPDU(target);

            pdu.add(new VariableBinding(new OID(oid)));
            pdu.setRequestID(new Integer32(SNMPRequestIdHandler.getNextRequestId()));

            logger.debug("SNMP Agent : " + target.getAddress() + " OID [" + oid + "] , Context : " + context + ", PDU Request Id : " + pdu.getRequestID());

            ResponseEvent response = snmp.send(pdu, target, transport);

            // Process Agent Response
            if (response != null) {
                PDU responsePDU = response.getResponse();

                if (response.getError() != null) {
                    logger.info("SNMP Agent : " + target.getAddress() + " Response Error : " + response.getError() + " , Context : " + context);
                    response.getError().printStackTrace();
                }

                if (responsePDU != null) {
                    logger.debug("SNMP Agent : " + target.getAddress() + " OID [" + oid + "] , Context : " + context + ", PDU Response Id : " + responsePDU.getRequestID());

                    int errorStatus = responsePDU.getErrorStatus();
                    int errorIndex = responsePDU.getErrorIndex();
                    String errorStatusText = responsePDU.getErrorStatusText();

                    if (errorStatus == PDU.noError) {
                        if (responsePDU.getVariableBindings() != null && responsePDU.getVariableBindings().size() > 0) {
                            result = new SNMPValue(responsePDU.getVariableBindings().get(0));
                        } else {
                            logger.error("SNMP Agent : " + target.getAddress() + " Error: Empty or null  OID [" + oid + "] , Context : " + context);
                        }
                    } else {
                        logger.error("SNMP Agent : " + target.getAddress() + " Error: Request Failed.  OID [" + oid + "] , Context : " + context + ", Error Status : " + errorStatus);
                        throw new AgentException("SNMP Agent : " + target.getAddress() + " Error: Request Failed.  OID [" + oid + "] , Context : " + context + ", Error Status : " + errorStatus);
                    }
                } else {
                    logger.error("SNMP Agent : " + target.getAddress() + " Error: Response PDU is null  OID [" + oid + "] , Context : " + context);
                    throw new AgentException("SNMP Agent : " + target.getAddress() + " Error: Response PDU is null  OID [" + oid + "] , Context : " + context);
                }
            } else {
                logger.error("SNMP Agent : " + target.getAddress() + " Error: Agent Timeout.  OID [" + oid + "] , Context : " + context);
                throw new AgentException("SNMP Agent : " + target.getAddress() + " Error: Agent Timeout.  OID [" + oid + "] , Context : " + context);
            }

        } catch (IOException e) {
            long endTime = System.currentTimeMillis();
            long timeToRun = endTime - startTime;
            logger.error("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is failed for OID : " + oid + " , Context : " + context + ", Execution Time : " + timeToRun);
            throw new AgentException(e);
        } finally {
            stop();
        }

        long endTime = System.currentTimeMillis();
        long timeToRun = endTime - startTime;

        if (result != null) {
            logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is finished for OID : " + oid + " , Context : " + context + ", Record Count : " + 1 + ", Execution Time : " + timeToRun);
        } else {
            logger.debug("SNMP Agent : " + snmpAgentConfig.getLoopbackip() + " SNMP " + "GET" + " is finished for OID : " + oid + " , Context : " + context + ", Record Count : " + 0 + ", Execution Time : " + timeToRun);
        }

        return result;
    }

}

------------

IP2

new Thread(){

run{
     SNMPValue data = snmpFetcher.get(oid);
}


IP3

new Thread(){

run{

     SNMPValue data = snmpFetcher.get(oid);
}

如果只需要数字:)

这是演示click

答案 21 :(得分:-1)

使用ng-only-number仅允许数字,例如:

<input type="text" ng-only-number data-max-length=5>

答案 22 :(得分:-2)

 <input
    onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||                         
    event.charCode == 0 || event.charCode == 46">