Reputation: 4449
My requirements
I have business requirements that make it necessary to do manual validation because the validation rules would be less or more strict, depending on the context in which you will enter a specific screen.
Also, it is possible that multiple instances of the same view (and as a result, the same controller) are loaded simultaneously.
Current attempt
Consider this Plunkr:
It uses the following function to do validation:
self.SaveAndValidate = function(validationContext){
var validationRules = self.GetValidationContext(validationContext);
self.RemoveAllClassInfo();
angular.forEach(validationRules, function(value){
$('#' + value.Field).addClass('mandatory');
})
}
As you will notice you can save for a different context, which will result in different fields being indicated as mandatory.
The question
As you will notice clicking the buttons of the second form doesn't work as expected, because they are targeting the first form, not the second. And that makes sense, because I'm using jQuery to target the input fields using specific field names. In this case, they exist twice on the same page, so the first occurrence is targeted.
Upvotes: 1
Views: 278
Reputation: 1009
You ought to rethink your way of adding the mandatory class. Maybe create a custom directive, or simply a ng-class={'mandatory' : isMandatory(yourId) } where isMandatory(id) iterates over your list to decide if it's a mandatory field.
Otherwise the Best practice would be to take a look at ng-form and use the ng-invalid ng-touched classes. https://docs.angularjs.org/guide/forms
And finaly, please don't use JQuery in your angularJS controller.
Upvotes: 1