【问题标题】:Why is my angular directive (using compile) blocking input in some scenarios?为什么我的角度指令(使用编译)在某些情况下会阻止输入?
【发布时间】:2017-04-06 23:41:13
【问题描述】:

我编写了一个指令,它根据条件添加一个类 - 请参阅问题底部的 sn-p。

它在以下必填字段的简单使用场景中按预期工作:

<input type="text" name="lastName" ng-model="$crtl.lastName" my-directive="$crtl.isLastNameValid()" required>

但是在以下场景中,我有两个使用 ng-required 的依赖元素,它会阻止我最初不输入的元素上的输入。

即如果我输入email,它会阻止输入mobile,反之亦然——除此之外其他都可以,用作:

<input type="email" id="email" name="email" ng-model="$ctrl.emailAddress"
   ng-required="$ctrl.mobileNumber.length === 0" my-directive="$ctrl.isEmailValid()">  

<input type="tel" id="mobile" name="mobile" ng-model="$ctrl.mobileNumber"
   pattern="(?:\+?61|0)4 ?(?:(?:[01] ?[0-9]|2 ?[0-57-9]|3 ?[1-9]|4 ?[7-9]|5 ?[018]) ?[0-9]|3 ?0 ?[0-5])(?: ?[0-9]){5}" 
   ng-required="$ctrl.emailAddress.length === 0" my-directive="$ctrl.isMobileValid()">

我哪里错了?我正在根据传入的条件编译元素,我假设它与此有关?

export const myDirective = ($compile: ng.ICompileService): ng.IDirective => {
    return {
        restrict: 'A',
        scope: true,
        compile: (element: ng.IAugmentedJQuery, attrs: ng.IAttributes): ng.IDirectivePrePost => {

            var condition = attrs['myDirective'];
            element.removeAttr('my-directive');

            if (condition) {
                element.attr('ng-class', `{ "validation-error": ${condition} }`);

                return {
                    pre: () => { },
                    post: ($scope: ng.IScope, element: ng.IAugmentedJQuery) => {
                        $compile(element)($scope);
                    }
                };
            }

            return {
                pre: () => { },
                post: () => { }
            };
        }
    };
};

【问题讨论】:

    标签: javascript angularjs typescript angularjs-directive


    【解决方案1】:

    如果您想要一个基于角度表达式定义的条件添加和删除类的指令:

    app.directive("myDirective", function () {
        return function postLink (scope, elem, attrs) {
            scope.$watch(attrs.myDirective, function(newBool) {
                if (newBool) {
                    attrs.$addClass("validation-error");
                } else {
                    attrs.$removeClass("validation-error");
                };
            });
        };
    });
    

    在每个摘要循环中,该指令都会评估由 my-directive 属性定义的 Angular 表达式,如果表达式发生变化,它会根据 Angular 表达式的真实性添加或删除 validation-error 类。

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2021-09-22
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多