Can I programmatically apply Angular validation directives inside a custom directive?

后端 未结 5 1406
[愿得一人]
[愿得一人] 2020-12-29 20:05

I have found great many occurrences of the following pattern for html inputs, this being for phone numbers:



        
5条回答
  •  情话喂你
    2020-12-29 21:01

    You are going in the opposite way, because you are assuming that directives are that much laborious to maintain and want to keep one to give all the validation you need, depending on the element.

    That's an interesting approach but you need to be warned about the modularity of this approach: give this much of labour to one directive only is counterintuitive over the best practices of doing a "pure Angular way" to do the things.

    If you want to proceed with this idea, I suggest you to look over the ngModelController (AngularJS Docs) properties, that can be injected on link() function of one directive. More precisely, the $validators.

    You can add how many $validators to a NgModel controller you want.

    During your validation, you can set/unset validity to the element returning a boolean:

    app.directive('validator', function () {
        var definition = {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModel) {
                // Return if no ngModelController
                if (!ngModel) {
                    return;
                }
    
                ngModel.$validators.validateLength = function (modelValue, viewValue) {
                    // modelValue === the value of the ngModel, on the script side
                    // viewValue === the value of the ngModel, on the HTML (rendered) side
                    // 
                    // you can set-up $parsers, $formatters, $validators, etc, to handle the element
    
                    return !(modelValue.length > 20);
                }
            }
        };
    
        return definition;
    });
    

    I suggest you to read more about this implementation because certain operations can interrupt the flux of $digest cycles on angular over the manipulated element.

    Edit 1:

    Like I've mentioned on the comments, here's a Plunkr with an working example.

提交回复
热议问题