I am working on an application that automatically saves changes when the user changes something, for example, the value of an input field. I wrote an autosave directive that is added to all form fields that should automatically trigger save events.
template:
<input ng-model="fooCtrl.name" autosave> <input ng-model="fooCtrl.email" autosave>
directive:
.directive('autosave', ['$parse', function ($parse) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { function saveIfModelChanged () {
So far, all this works fine for me. However, when I add validation to the mix, for example by checking that the input field is a valid email address, the modelValue parameter is set to undefined as soon as the viewValue variable is changed to an invalid email address.
What I would like to do is: Remember the last valid modelValue and use it when autosaving. If the user changes the email address to be invalid, the object containing name and email must be stored on the server. Using the current valid name and the last valid email .
I started by saving the last valid modelValue as follows:
with verification added:
<input type="email" ng-model="fooCtrl.name" autosave required> <input ng-model="fooCtrl.email" autosave required>
with saving lastModelValue:
.directive('autosave', ['$parse', function ($parse) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { var lastModelValue; function saveIfModelChanged () {
My question is how to use lastModelValue when saving, but keeping an invalid value in the view?
EDIT:
Another feature suggested by Jugnu below will wrap and manipulate the assembly in validators.
I tried to do the following: wrap all existing validators and remember the last valid value, restore it if the checks fail:
Object.keys(ngModel.$validators).forEach(function(validatorName, index) { var validator = ngModel.$validators[validatorName]; ngModel.$validators[validatorName] = createWrapper(validatorName, validator, ngModel); }); function createWrapper(validatorName, validator, ngModel){ var lastValid; return function (modelValue){ var result = validator(modelValue); if(result) { lastValid = modelValue; }else{
But I'm not sure how to continue this approach. Can I set the model value without using AngularJS and try to confirm this new setpoint?