Naomi
Naomi

Reputation: 718

Re-set all forms to pristine status from the bottom up

We have smDateTimePicker directive which is rather complex. This time picker control can be part of another directive and that directive can be placed into the form (or a tab). In that smDateTimePicker directive we have code resetting form to pristine status (and I added last 2 lines just now):

DateTimePicker.prototype.setPristine = function () {
        if (this.form) {
            this.form.$setPristine();

            if (this.form.$$parentForm.$dirty) {
                this.form.$$parentForm.$setPristine();
            }
            if (this.form.$$parentForm.$$parentForm && this.form.$$parentForm.$$parentForm.$dirty) {
                this.form.$$parentForm.$$parentForm.$setPristine();
            }
        }
    };

I don't like that I need to use $$parentForm property and I need to use it twice for my particular case. Besides, what if I have deeper hierarchy? Is there a cleaner way to re-set all forms to pristine from the bottom up?

Upvotes: 0

Views: 334

Answers (1)

Diablo
Diablo

Reputation: 169

See if this works for you. You may have to do minor changes if needed:

DateTimePicker.prototype.setPristine = function () {
        if (this.form) {
            setPristineToForm(this.form);
        }
    };

    // Recursive method - goes up the hierarchy of forms
    var setPristineToForm = function (form) {
        if (form) {
            //Check if a parent form exists. If it does, set parent's pristine 
            var parentForm = this.form.$$parentForm;

            if (parentForm) {
                setPristineToForm(parentForm);
            }
            else { //No parent exist. Set pristine to current form if it is dirty.
                if (form.$dirty)
                    form.$setPristine();
            }
        }
    };

Upvotes: 1

Related Questions