Skip to content

Commit 8d89396

Browse files
committed
Push validation state to a field via events
Trying out using events to push validation state and possible message to a specific field.
1 parent 2a83564 commit 8d89396

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

src/services/decorators.js

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ angular.module('schemaForm').provider('schemaFormDecorators',
189189
// Do we have a condition? Then we slap on an ng-if on all children,
190190
// but be nice to existing ng-if.
191191
if (form.condition) {
192-
angular.forEach(element.children(),function(child) {
192+
angular.forEach(element.children(), function(child) {
193193
var ngIf = child.getAttribute('ng-if');
194194
child.setAttribute(
195195
'ng-if',
@@ -204,6 +204,45 @@ angular.module('schemaForm').provider('schemaFormDecorators',
204204
$compile(element.contents())(scope);
205205
});
206206

207+
// Where there is a key there is probably a ngModel
208+
if (form.key) {
209+
// It looks better with dot notation.
210+
scope.$on(
211+
'schemaForm.error.' + form.key.join('.'),
212+
function(event, error, validationMessage, validity) {
213+
if (validationMessage === true || validationMessage === false) {
214+
validity = validationMessage;
215+
validationMessage = undefined;
216+
}
217+
218+
if (scope.ngModel && error) {
219+
if (scope.ngModel.$setDirty()) {
220+
scope.ngModel.$setDirty();
221+
} else {
222+
// FIXME: Check that this actually works on 1.2
223+
scope.ngModel.$dirty = true;
224+
scope.ngModel.$pristine = false;
225+
}
226+
227+
// Set the new validation message if one is supplied
228+
// Does not work when validationMessage is just a string.
229+
if (validationMessage) {
230+
if (!form.validationMessage) {
231+
form.validationMessage = {};
232+
}
233+
console.log('settings validationMessage', validationMessage)
234+
form.validationMessage[error] = validationMessage;
235+
}
236+
237+
scope.ngModel.$setValidity(error, validity === true);
238+
239+
// Setting or removing a validity can change the field to believe its valid
240+
// but its not. So lets trigger its validation as well.
241+
scope.$broadcast('schemaFormValidate');
242+
}
243+
})
244+
}
245+
207246
once();
208247
}
209248
});

0 commit comments

Comments
 (0)