简体   繁体   English

角度指令添加指令

[英]Angular Directive to add a Directive

I'm trying to create a directive wrapper for the ng-minlength and ng-maxlength directives. 我正在尝试为ng-minlength和ng-maxlength指令创建指令包装。 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. 都可以使用添加的ng-minlength属性正确编译,但是ng-minlength指令似乎不会以通常的方式影响字段的有效性。 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? 有人可以帮助我了解如何实现这一目标吗?

As noted above: 如上所述:

I did get this to work BY adding the compile service to the post link function 我确实通过将编译服务添加到post link函数来使其工作

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. 仅当不存在ng-指令并将其添加并设置attrs。$ observe('minLength')以在值更改时更新ng-minlength属性时,才重新编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM