带有已编译模板的angularjs验证指令无法反映dom的'max'属性更改

问题描述

我使用以下指令显示自定义验证:

 app.directive("validationMessages",['$compile',($compile: ng.ICompileService) => {
        return {
            require: "^form",replace: false,link: (scope,element,attrs,formCtrl) => {
                const fieldName = attrs["validationMessages"];
                const elementName = attrs["name"];
                const formName = formCtrl.$name;
                const elementFormKey = formName + "." + elementName;

                let html: string = `<div class="error" ng-show="${elementFormKey}.$invalid">`;

                for (const key in attrs) {
                    if (Object.prototype.hasOwnProperty.call(attrs,key)) {
                        const value = attrs[key];
                        switch (key) {
                           
                            case "ngMax":
                            case "max":
                                    html += `<small class="error ng-show="${
                                        elementFormKey}.$error.max">
                                        ${fieldName} must be less than or equal to ${value} abcd.
                                    </small>`;
                                
                                break;
                        }
                    }
                }
                html += "</div>";

                let template = angular.element(html);
                let parser = $compile(template);
                let parsed = parser(scope);
                element.after(parsed);
            }
        };
    }]);

代码显示类似这样的输入错误

<input class="form-control"
                       ng-model="Vm.c0"
                       name="C0"
                       validation-messages="Constant C0"
                       max="{{Vm.maxValue}}"
                      />

问题是,模板未反映对VM.maxValue的更改。 实际上,link函数仅运行一次。我需要watch吗? 为什么呢?

更新:

Finallay我想现在问题出在哪里了-{{ }}表达式: max =“ {{Vm.maxValue}}”

还有另一种方式传递Vm.maxValue吗?

解决方法

实际上,不会监视带有诸如{{}}之类的表达式绑定的属性的更改。 添加scope.watch()会有所帮助。