After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss.
Here is how my setup looks:
- I employ a directive to create a new form.
- The controller accesses the relevant form schema, which is utilized to generate fields in the view using
ng-repeat
. - These input and textarea fields are then linked to the controller through
ng-model
. - Upon field alteration or form submission, the controller forwards the form data to a validation service, which returns an error if needed, subsequently binding it to the DOM.
The challenge arises when attempting to implement a sanitation step before the validation process described in part 4. This step should update the controller data with the return value from a service method, refreshing the DOM binding and allowing the validation process to use the updated value. Despite updating the controller value itself, this change does not reflect in the DOM.
Below is snippet of the pertinent code:
View:
<div ng-repeat="(field, value) in form.schema">
<!-- ... -->
<textarea ng-model="form.data[field]" ng-model-options="{ updateOn: 'blur' }" ng-change="form.changed(field)"></textarea>
<div class="message">{{ form.errors[field] }}</div>
</div>
Controller:
// Controller submit method
ctrl.submit = function () {
var err;
for (var field in ctrl.schema) {
ctrl.data[field] = validationService.sanitizeField(ctrl.data[field], ctrl.schema[field]);
ctrl.errors[field] = validationService.validateField(ctrl.data[field], ctrl.schema[field]);
if (ctrl.errors[field] !== undefined) {
err = true;
}
}
if (err) {
return;
}
// Proceed ...
Service:
// Public field sanitation method
var sanitizeField = function (value, schema) {
try {
// Try sanitation
}
catch (e) {
// Error
}
return value;
}
While logging the new value of ctrl.data[field]
in the controller post-sanitation yields the correct output, this result is correctly passed to the subsequent validateField
method. Nonetheless, the altered data value fails to update in the DOM.
Initially, I suspected issues pertaining to scope application or promises. However, modifying the service and controller accordingly did not resolve the problem. Furthermore, wrapping the return value of sanitation in an object proved ineffective.
Interestingly, changing the return value in the service from the value
variable to a primitive value like 'test'
, prompts an update in the DOM upon return.
Similarly, errors returned from the service validation method (also strings rather than variables) are displayed appropriately in the DOM.
Despite conducting extensive research on the topic, I have been unable to find solid answers. Any insights would be greatly appreciated!