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

5
  • Forgot to mention I'm using angularjs version 1.6.5 Commented Sep 7, 2018 at 8:20
  • ng-repeat and ng-if have their own scope. Maybe you can try writing it as $parent.field.templateOptions.pattern or use controllerAs syntax to reach the scope of the controller Commented Sep 7, 2018 at 8:24
  • Shouldn't ng-if="field-type=='input'" be ng-if="field.type=='input'" ?? Commented Sep 7, 2018 at 8: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 Commented Sep 7, 2018 at 9: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+' Commented Sep 7, 2018 at 9:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.