javascript 是否可以将 ng-pattern 与变量一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28731451/
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
Is it possible to use ng-pattern with a variable
提问by abcf
I'm terrible with regular expressions but I was wondering if it was possible to use ng-pattern with a variable
我对正则表达式很糟糕,但我想知道是否可以将 ng-pattern 与变量一起使用
For example,
例如,
ng-pattern="/^{{validationCode}}$/"
where validationCode is a variable attached to $scope in a controller
其中validationCode 是附加到控制器中$scope 的变量
// Inside Controller
$scope.validationCode = 'response returned from server'
If
如果
$scope.validationCode = 1234123412351234
then the ng-pattern would be
那么 ng 模式将是
ng-pattern="/^1234123412351234$/"
But this isn't working and it seems like I need to create a custom directive which I don't really want
但这不起作用,似乎我需要创建一个我并不真正想要的自定义指令
回答by New Dev
ng-pattern
expects a regex expression.
ng-pattern
需要一个正则表达式。
From Angular's documentationabout ng-pattern
:
从角的文档有关ng-pattern
:
Sets pattern validation error key if the value does not match the
RegExp
pattern expression. Expected value is/regexp/
for inline patterns orregexp
for patterns defined as scope expressions.
如果值与
RegExp
模式表达式不匹配,则设置模式验证错误键。预期值适用/regexp/
于内联模式或regexp
定义为范围表达式的模式。
In other words, you could create a RegExp in the controller:
换句话说,您可以在控制器中创建一个 RegExp:
$scope.pattern = new RegExp(patternFromServer);
and use it:
并使用它:
<input ng-model="foo" ng-pattern="pattern">