0
votes

I'm trying to create a directive wrapper for the ng-minlength and ng-maxlength directives. The purpose of these wrapper directives is to populate the input model with the max and min lengths to be able to create custom validation messages. My directive looks like this

var directive = angular.module('selfservice.directives', []).directive
directive('minlength', [function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        compile: function compile(tElement, tAttrs, transclude) {
            return {
                pre: function preLink(scope, elem, attrs) {
                    scope.minlength = attrs['minlength'];
                    elem.attr('ng-minlength', scope.minlength);
                    elem.removeAttr('minlength');
                }
            }
        }
    }
}])

It all compiles correctly with the ng-minlength attribute added, however the ng-minlength directive does not seem to be affecting the field validity in the usual way. I added the function to the precompile specifically so that it would compile all together in the regular digest cycle as if it had been there from the beginning, but that does not seem to be working. Can someone help me understand how to accomplish this?

1
Normally you would call $compile(element)(scope) to get angular to pay attention your new ng- directives, but you're removing your own directive attribute at the same time? I'm not sure what affect that would have. Also I think it might need to be on the post-link function... If you didn't remove your own directive attribute it may cause unwanted recursion... - Jason Goemaat
I did get this to work just before I saw this post by doing exactly what you said, adding the compile service to the post link function. Also I'm removing my own directive to prevent any looping that may be caused if I had it there. - richbai90
The problem with removing your own directive is that you are setting the attribute values for the ng- directives, so I don't think they would update if you change the value on your scope. Maybe leave your directive there and only recompile if the ng- directive wasn't there and you added it, as well as set up an attrs.$observe('minLength') to update the ng-minlength attribute when the value changes? - Jason Goemaat
That's a good suggestion thanks. - richbai90

1 Answers

0
votes

As noted above:

I did get this to work BY adding the compile service to the post link function

Only recompile if the ng- directive wasn't there and you added it, as well as set up an attrs.$observe('minLength') to update the ng-minlength attribute when the value changes.