2016-08-23 66 views
0

我想限制用户键入除“打开”或“关闭”字符串值以外的其他值。角JS文本框验证允许特定的文本限制其他值

这意味着用户只能键入“打开”或“关闭”文本,而且maxlength是6.为此创建了指令,但仍然允许其他文本值,如何捕获或允许用户只键入这两个文本值。

plunkr链接

http://plnkr.co/edit/LFbPbRAMyYZGhTZ1F7GU?p=preview

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 


}); 

app.directive('wmBlock', function ($parse) { 
    return { 

     link: function (scope, elm, attrs) { 

      elm.bind('keypress', function(e){ 

      if(scope.foo==="open" || scoe.foo==="closed"){ 
       return true; 
      } 
      else 
      { 
       e.preventDefault(); 
       return false; 
      } 
      } 
      }); 
     } 
    } 
}); 
+0

不错的尝试,但是当你有两个已知选项的简单要求.......你为什么不尝试用一个下拉菜单 –

+0

http://jsfiddle.net/vfsHX/2422/ – SivaRajini

+0

不错的工作.. ..... –

回答

0
app.directive('wmBlock', function ($browser, $parse) { 
    return { 

    link: function ($scope, $element, $attrs, ngModelCtrl) { 

     $element.bind('keypress', function(e){ 

     $browser.defer(
      function(){ 

      var modelGetter = $parse($attrs['ngModel']); 

      var value = modelGetter($scope); 
      var expression = new RegExp(/^(open|close)$/); 
      if(expression.test(value)) 
       alert("founded!"); 

      }); 


     }); 
    } 
    } 
}); 
0

我已经这样做了使用$腕表功能

app.directive('isNumber', function() { 
    return { 
     require: 'ngModel', 
     link: function (scope) {  
      scope.$watch('opennumber', function(newValue,oldValue) { 
      if(newValue=="o" || newValue=="c") return; 
      if(newValue=="op" || newValue=="ope" || newValue=="open") return; 
      if(newValue=="cl" || newValue=="clo" || newValue=="clos" || newValue=="close" || newValue=="closed") return; 

       if (newValue) { 
        scope.opennumber = oldValue; 
       } 
      }); 
     } 
    }; 
}); 

的jsfiddle

http://jsfiddle.net/vfsHX/2422/