1

I have a form with 3 input fields. But I want to use the form also for other pages. Therefore I have reduced the form. At the beginning I've defined the view as follows:

View:

<form class="form-horizontal" name="editForm" novalidate>
  <div ng-repeat="elements in form">
    <div class="form-group-sm has-feedback" ng-repeat="el in elements.items" ng-class="{ 'has-error' : hasError(editForm), 'has-success' : hasSuccess(editForm) }">
       <label class="control-label" for="{{el.id}}">{{el.label}}</label>
       <input type="{{el.fieldType}}"
              class="form-control" 
              placeholder="{{el.label}}"  
              name="{{el.name}}" 
              id="{{el.id}}"
              ng-model="selected[el.model]" 
              ng-disabled="{{el.disabled}}"
              ng-pattern="el.pattern" 
              ng-required="{{el.required}}"
       />
       <p class="help-block" ng-show="editForm.{{el.name}}.$error.required && editForm.{{el.name}}.$touched">Field is required.</p>
       <p class="help-block" ng-show="editForm.{{el.name}}.$error.pattern">Thats the pattern error message.</p>
   </div>
 </div>    
</form>

I want to outsource the error messages / validation in a function. The error messages in the p-Tag don't work.

I've tried this in my Ctrl:

$scope.hasError = function (form) {
   return form.Firstname.$invalid && form.Firstname.$dirty;
}

$scope.hasSuccess = function (form) {
   return form.Firstname.$valid;
}

That is only for the inputfield Firstname. But how can I define this dynamically for all fields (firstname, lastname, age)?

2 Answers 2

1

Pass dynamic field name into function:

ng-class="{ 'has-error' : hasError(editForm, el.name), 'has-success' : hasSuccess(editForm, el.name) }"

and in controller use bracket notation to access variable ngModelController:

$scope.hasError = function (form, name) {
   return form[name].$invalid && form[name].$dirty;
};

$scope.hasSuccess = function (form, name) {
   return form[name].$valid;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thx for the solution but is it possible to improve the code in ngShow? I mean to outsource in a function or directive or similar??
1

Try this

 <p class="help-block" ng-show="editForm[el.name].$error.required && editForm[el.name].$touched">Field is required.</p>
 <p class="help-block" ng-show="editForm[el.name].$error.pattern">Thats the pattern error message.</p>

2 Comments

is it possible to outsource the code in ngShow in a function? What is best practice for this kind of code?

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.