ng-pattern从角常量使用正则表达式 [英] ng-pattern to use regex from angular constants
问题描述
-简短版本-
如何从角度常数中获取ng-pattern以使用正则表达式?
-长版-
我正在处理一个庞大的Angular 1项目,我们有多种形式.这些表格中有很多都具有相同的字段,例如邮政编码和电话号码.我想寻找一种使用ng-pattern的一致方法,但是将regex放在一个位置以保持一致性.我想为此使用角度常数,但是我无法让ng-pattern取值,而且我也弄不清为什么.
-我所做的-
我确实找到了这个答案 Angularjs动态ng模式验证用于动态放置正则表达式进入ng-pattern并尝试了这种方法,但该方法似乎不适用于角度常数.
我尝试将正则表达式存储为字符串并将其转换为HTML.我尝试使用返回正则表达式值的函数.
-问题的jsfiddle-
https://jsfiddle.net/Michael_Warner/692deLsb/8/ >
问题出在这行代码.
ng-pattern ="patterns.zip"
如果我将正则表达式直接嵌入ng-pattern中,那么它将如您在小提琴中看到的那样工作
ng-pattern ="/^ \ d {5}(?:-\ d {4})?$/"
您可以通过两种方式进行操作:
1:作为字符串 literal ,必须加双斜杠时:
.constant("formPattern",{zip:新RegExp("^ \\ d {5}(?:-\\ d {4})?$")})
2:作为正则表达式:
.constant("formPattern",{邮编:/^ \ d {5}(?:-\ d {4})?$/})
两个人都在你的小提琴中工作.
--Short Version--
How do you get ng-pattern to use regex from angular constants?
--Long Version--
I'm working on a huge Angular 1 project and we have multiple forms. A lot of these forms have the same fields like Zip and Phone Number. I wanted to look for a consistent way to use ng-pattern but have the regex in one location for consistency. I want to use angular constants for this but I can't get ng-pattern to take the value and I can't figure out why.
--What I've done--
I did find this answer Angularjs dynamic ng-pattern validation for placing regex dynamically into ng-pattern and I tried that but that method didn't seem to work for angular constants.
I've tried storing the regex as strings and converting it in the HTML. I've tried using a function that returns the regex value.
--jsfiddle of the issue--
https://jsfiddle.net/Michael_Warner/692deLsb/8/
The issue goes down to this line of code.
ng-pattern="patterns.zip"
If I embed the regex into ng-pattern directly then it will work as you can see in the fiddle
ng-pattern="/^\d{5}(?:-\d{4})?$/"
You can do it in two ways:
1: As string literal, when you must double slashes:
.constant("formPattern", {
zip: new RegExp("^\\d{5}(?:-\\d{4})?$")
})
2: As regular expression:
.constant("formPattern", {
zip: /^\d{5}(?:-\d{4})?$/
})
Both worked in your fiddle.
这篇关于ng-pattern从角常量使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!