javascript AngularJS 的 IP 地址掩码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17025384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:49:30  来源:igfitidea点击:

Ip Address mask for AngularJS

javascriptjqueryangularjsmaskedinput

提问by z_inx

Does Anyone know a ip address mask plugin for AngularJS?

有人知道 AngularJS 的 IP 地址掩码插件吗?

Because I tried to use the "Jquery Input IP Address Control", but it's not working. When I try to use it, the "ngModel" attribute doesn't get the value of the textfield. In the screen I can see the value inside the textfield, however, if I do ".value()" in the element, it return a "" value. The same thing occur when I see the value of the $scope element by using console.log().

因为我尝试使用“Jquery 输入 IP 地址控制”,但它不起作用。当我尝试使用它时,“ngModel”属性没有获取文本字段的值。在屏幕中,我可以看到文本字段中的值,但是,如果我在元素中执行“.value()”,它会返回一个“”值。当我使用 console.log() 查看 $scope 元素的值时,也会发生同样的事情。

Can anyone help me?

谁能帮我?

Thanks!

谢谢!

Edit: SOLVED

编辑:已解决

People, problem solved.

人,问题解决了。

I used this directive available in http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController:

我使用了http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController 中提供的这个指令:

app.directive('contenteditable', function() {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function(scope, element, attrs, ngModel) {
            if(!ngModel) return; // do nothing if no ng-model

            // Specify how UI should be updated
            ngModel.$render = function() {
            element.html(ngModel.$viewValue || '');
           };

           // Listen for change events to enable binding
           element.bind('blur keyup change', function() {
           scope.$apply(read);
           });
           read(); // initialize

           // Write data to the model
           function read() {
            ngModel.$setViewValue(element.val());
           };
       }
    };
});

After I used this directive, the Jquery Plugin worked fine. Probably because now the ngNodel is getting the element.val(). Before, I think it was getting the element.text().

使用此指令后,Jquery 插件工作正常。可能是因为现在 ngNodel 正在获取 element.val()。之前,我认为它正在获取 element.text()。

回答by vittore

I'm just wondering why you need this in the first place. What about just using [ngPattern][1]directive and placeholderattribute ?

我只是想知道为什么你首先需要这个。只使用[ngPattern][1]指令和placeholder属性怎么样?

 <div ng-app='app' ng-controller='myCtrl' ng-form='myForm'>
   <input type='text' ng-model='ip' 
          ng-pattern='/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/' 
          placeholder='xxx.xxx.xxx.xxx'  />
   value : {{ ip }}    
 </div>

Several notes:

几个注意事项:

  • commenters adding ^and $quantifiers to the regex. You don't need to do that since angular adding them for you inside ng-patterndirective (see angular.js source code for ng-pattern)

  • I do not belive that regex is good match for checking if each number is in [0,255] range. What I would rather do is implement ng-ipaddress directive, working with ngModelControllerdirectly. (see js-fiddle or github link)

    var app = angular.module('app',[])
    
    .directive('ipAddress', function ipAddress(){
    
      return {
        restrict:'A',
        require:'?ngModel',
        link: function(scope, elm, attr, ctrl){         
          if (!ctrl) return;        
          ctrl.$parsers.push(function(viewValue){
            if (!viewValue) return null;          
            var isvalid = isValidIp(viewValue)          
            return isvalid ? viewValue : null;                   
          })
        }          
      }
    
      function isValidIp(value){
           var arr = value.split('.')
           var r = /^\d{1,3}$/;
           return arr.length === 4 && arr.map(function(e){
            return ( r.test(e) && ((e|0) >= 0) && ( (e | 0) <= 255))            
           }).every(function(e){ return e })                 
      }   
    })
    
  • 评论者添加^$量词的正则表达式。您不需要这样做,因为 angular 会在ng-pattern指令中为您添加它们(请参阅 angular.js 源代码以获取 ng-pattern

  • 我不相信正则表达式非常适合检查每个数字是否在 [0,255] 范围内。我宁愿做的是实现 ng-ipaddress 指令,ngModelController直接使用。(见 js-fiddle 或 github 链接)

    var app = angular.module('app',[])
    
    .directive('ipAddress', function ipAddress(){
    
      return {
        restrict:'A',
        require:'?ngModel',
        link: function(scope, elm, attr, ctrl){         
          if (!ctrl) return;        
          ctrl.$parsers.push(function(viewValue){
            if (!viewValue) return null;          
            var isvalid = isValidIp(viewValue)          
            return isvalid ? viewValue : null;                   
          })
        }          
      }
    
      function isValidIp(value){
           var arr = value.split('.')
           var r = /^\d{1,3}$/;
           return arr.length === 4 && arr.map(function(e){
            return ( r.test(e) && ((e|0) >= 0) && ( (e | 0) <= 255))            
           }).every(function(e){ return e })                 
      }   
    })
    

jsfiddlegithub

jsfiddle github

回答by Valera Tumash

Assuming @Jayesh answer and made some shortenings here is the resulting correct version with pattern for 0.0.0.0through 255.255.255.255

假设@Jayesh 回答并在此处进行了一些缩短,则生成的正确版本的模式为0.0.0.0255.255.255.255

<input type="text"
       id="static_ip"
       name="static_ip"
       placeholder="Static IP"
       ng-model="device.static_ip"
       ng-pattern="/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/"
       ng-model-options="{ updateOn: 'blur' }"
    />

I have added ng-model-optionsin order that validation be triggered only on blur effect so the error class if any only shows up after changing focus to another field. However it works only for AngularJS 1.3+

我添加了ng-model-options以便仅在模糊效果上触发验证,因此错误类(如果有)仅在将焦点更改为另一个字段后才会出现。但是它只适用于 AngularJS 1.3+