Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  105] [ 6]  / answers: 1 / hits: 17032  / 11 Years ago, fri, december 20, 2013, 12:00:00

I have a form that I am validating with Angular.js and I want to pragmatically set the dirty state on a child element of a form. However, the child element is in an isolated scope in a directive. How can I set that input element to ng-dirty from the parent scope?



Example code:



<form name=parentForm>

<!-- How can I validate an input element inside this directive-->
<childDirective required />

</form>


Example Child Directive:



<div>
<input type=text ng-form name=childForm required/>
</div>

More From » forms

 Answers
21

I made a utility method in Typescript to handle this in a more holistic way. This can $setDirty on all elements with an error at any depth. I know you're asking about a specific field in your question, but this could be a more useful tool for certain problems you may be solving for.



class AngularFormUtil
{
static RecursiveSetDirty(form: ng.IFormController)
{
form.$setDirty();
for (let errorProp in form.$error)
{
if (!form.$error.hasOwnProperty(errorProp))
return;

for (let error of form.$error[errorProp])
{
if (error.$setDirty) {
AngularFormUtil.RecursiveSetDirty(error);
}
}
}
}
}


Just plug in the form:



AngularFormUtil.RecursiveSetDirty($scope.parentForm);


Plain JS compiled version:



var AngularFormUtil = (function () {
function AngularFormUtil() {
}
AngularFormUtil.RecursiveSetDirty = function (form) {
form.$setDirty();
for (var errorProp in form.$error) {
if (!form.$error.hasOwnProperty(errorProp))
return;
for (var _i = 0, _a = form.$error[errorProp]; _i < _a.length; _i++) {
var error = _a[_i];
if (error.$setDirty) {
AngularFormUtil.RecursiveSetDirty(error);
}
}
}
};
return AngularFormUtil;
}());

[#73629] Thursday, December 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;