【问题标题】:Can AngularJS "value" services hold a regex?AngularJS“价值”服务可以持有正则表达式吗?
【发布时间】:2015-04-21 23:37:18
【问题描述】:

我创建了一个有角度的Value 服务,该服务包含一个正则表达式,而不是将其附加到控制器实例,即

myService.value('regexValue' {PASSWORD_REGEX: /passwordregex/})


myController(regexValue) { 
    this.regexValue = regexValue.PASSWORD_REGEX;  
}

然后我尝试在输入字段data-ng-pattern 属性中使用此值

<input type="password" data-ng-pattern="myController.regexValue.PASSWORD_REGEX">

然而,这似乎不适用于 ng-pattern 指令。

我的问题是如何让它发挥作用?

【问题讨论】:

    标签: javascript angularjs angularjs-service


    【解决方案1】:

    你的理论是正确的。 ng-pattern 接受模式的字符串表示、内联模式或范围变量。唯一的问题是您将控制器下的 regexValue.PASSWORD_REGEX 定义为 controller.regexValue,然后尝试访问 controller.regexValue.PASSWORD_REGEX。

    要么做:

    myController(regexValue) { 
    
        this.regexValue = regexValue.PASSWORD_REGEX;  
    }
    
    <input type="password" data-ng-pattern="myController.regexValue">
    

    myController(regexValue) { 
        this.regexValue = regexValue;  
    }
    
    <input type="password" data-ng-pattern="myController.regexValue.PASSWORD_REGEX">
    

    工作小提琴:http://jsfiddle.net/yrq18bbh/3/

    【讨论】:

      【解决方案2】:

      ng-pattern 想要模式的字符串表示(不带 /),因此您可以通过访问 source 属性从您的正则表达式中获取它:

      <input type="password" data-ng-pattern="myController.regexValue.PASSWORD_REGEX.source">
      

      console.log(/foo+bar*?/.source)

      【讨论】:

      猜你喜欢
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2013-12-23
      • 2015-03-21
      相关资源
      最近更新 更多