shane shane - 3 months ago 10
AngularJS Question

angular-wysiwyg form validation

I'm trying to use

angular-wysiwyg
and form validation. Instead of using the standard
form.textArea.$dirty
I've been updating a flag on the scope:



$scope.onTextChange = function (value) {
$scope.textContent = value;
$scope.isContentDirty = true;
...
}





Then I can use the property on my button:



<button ng-diabled="isContentDirty"></button>





But I'd prefer to do something like this:



<wysiwyg name="myTextArea" ng-model="textContent"></wysiwyg>

<button ng-disabled="!form.myTextArea.$dirty></button>





How could I make this work?

Here's an open issue sort of related:

https://github.com/TerryMooreII/angular-wysiwyg/issues/43

Here are the docs for this directive: https://github.com/TerryMooreII/angular-wysiwyg#usage

Answer

I found a solution that made me happy enough. It turns out that you can check the validity of any form item by reference, ie:

myForm.editor.$error

which would reference errors on the "editor" form item here:

<form name="myForm">
    <wysiwyg name="editor"></wysiwyg>
</form>

When you go to the link step in the directive, you can set $parsers, which essentially allow you to invalidate your form if some conditions are met:

angular.module('foo').directive('wysiwyg', function() {
    return {
        restrict: 'E',
        require: 'ngModel', //the 'value' of the form item
        template: 'my template',
        link: function(scope, elem, attrs, ngModel) {

            function checkCustomError(viewValue) {
                valid = viewValue.someCondition === 'someValue';
                ngModel.$setValidity('customError', valid);
                return viewValue;
            }

            ngModel.$parsers.unshift(checkCustomError);
        }
    }
}

And the error would show up under formName.directiveName.$error.customError

There are other ways to invalidate the ngModel as well, such as putting ng-maxlength on the directive, but I thought this was the most informative way of explaining.

Documentation about form validation:

Custom Form Validation

Some useful tips about sub-forms / sub-form parts affecting the whole form that I wrote up as a result of my search:

Nested Forms

Comments