0

I've been stuck on a problem for a while now and I feel I've exhausted all efforts.

I have a dynamic form created using an ng-repeat, for some reason ng-pattern will not work in this scenario, ng-required works perfect though.

field.label = "test input"
field.key = "test_input"
field.type = "text"
field.templateOptions.type = "text"
field.templateOptions.required = true
field.templateOptions.pattern = "\\d+"

Here is the code:

<form name="form">
   <div ng-repeat="field in fields">
      <div ng-if="field-type=='input'">
         <label>{{field.label}}</label>
         <input 
             type="{{field.templateOptions.type}}" 
             name="{{field.key}}"
             ng-required="{{field.templateOptions.required}}"
             ng-pattern="{{field.templateOptions.pattern}}"
             ng-model="model[field.key]"
         />
         <div ng-show="form[field.key].$error.required">Required Field</div>
         <div ng-show="form[field.key].$dirty && form[field.key].$error.pattern">Numeric Field Required</div>
      </div>
   </div>

I've even tried using a ng-form inside the ng-repeat (this didnt work).

This works, however its not in a ng-repeat:

<form name="form">
    <label>test input</label>
    <input type="text"
            name="test_input"
            ng-required="true"
            ng-pattern="\\d+"
            ng-model="model" />
    <div ng-show="form.test_input.$error.required">Required Field</div>
    <div ng-show="form.test_input.$dirty && form.test_input.$error.pattern">Numeric Field Required</div>
</form>

Any help will be greatly appreciated, thanks

  • Forgot to mention I'm using angularjs version 1.6.5 – Darren Eccles Sep 07 '18 at 08:20
  • `ng-repeat` and `ng-if` have [their own scope](https://stackoverflow.com/a/36309836/8495123). Maybe you can try writing it as `$parent.field.templateOptions.pattern` or use _controllerAs_ syntax to reach the scope of the controller – Aleksey Solovey Sep 07 '18 at 08:24
  • Shouldn't ng-if="field-type=='input'" be ng-if="field.type=='input'" ?? – Sarvagya Saxena Sep 07 '18 at 08:39
  • Fixed it, it was the regex. I have two forms, one in an admin area (using umbraco 7 back office which uses angularjs 1.1.5) and a form for the front-end users which is using angularjs 1.6.5. It turns out this is valid and works in angularjs 1.1.5 - '/^\\d+$/', however for the example above, this works '\d+'. Thanks – Darren Eccles Sep 07 '18 at 09:30
  • So in my json I have '/^\\d+$/' for umbraco back office, and for the code to work above I have this is my view which removes the first and last two characters - {{field.templateOptions.pattern.substring(2, field.templateOptions.pattern.length-2)}} to this '\d+' – Darren Eccles Sep 07 '18 at 09:33

0 Answers0