在Angular指令中编译后,输入中的输入无效

时间:2016-12-10 16:31:18

标签: javascript angularjs validation angularjs-directive

我有一个指令,根据模型中的验证列表为输入添加自定义和本机验证。验证的值可以根据表单中其他地方的输入而改变(例如,enddate不应该在startdate之前)。

function questionValidations($compile, $parse) {
    var directive = {
        restrict: 'A',
        link: linker
    }

    return directive;

    function linker(scope, elem, attrs) {
        var validations = $parse(attrs.questionValidations)(scope);
        setValidations();

        function setValidations() {
            if (!validations || validations.length < 1) {
                return;
            }

            // Logic that adds/removes attributes following the parsed validations above                                           
            // Additionally a service is called to determine if 
            // the validation value should be watched. 
            // Watch calls setValidations.

            // Compile if there are new or removed attributes
            if (new || removed) {
                var newElem = angular.element(elem[0]);
                elem.replaceWith(newElem);
                $compile(newElem)(scope);
            }
        }
    }
}

添加/删除属性,验证似乎在某种程度上起作用,但删除了所有无效输入。 我尝试在this post之后的隔离范围内分配ngModel,但这并未改变行为。

当我使用以下代码进行编译时,验证可以按需运行(不知道为什么会这样)

         $compile(elem)(scope,
            function(clone) {
                elem.after(clone);
                elem.remove();
          });

但是,如果其中一个监视器调用了setValidations,则它仅在第一次编译该元素时。对于startdate示例,这意味着对于输入的第一个日期,enddate输入被编译得很好,但是当我更改输入时没有任何反应(在调用编译之前记录属性确实显示更新的值)。原始指令中的compile方法会重新编译模型更改,但会删除所有无效输入。

修改:添加了Plunker

看起来输入的去抖与它有关。不幸的是,我有一堆代码在我的ng-change上运行,我需要去抖动。

当我向我的ng-model-options添加allowInvalid:true时,不再删除

edit2:值。我对无效值并不感兴趣,所以我不想使用它。

0 个答案:

没有答案