指令中的编译函数不能正确求值

compile function in directive not evaluating correctly

本文关键字:不能 函数 编译 指令      更新时间:2023-09-26

我有一个名为validate的指令,它跨包了一个表单,并根据内置的angular输入验证指令自动验证表单。该指令的部分工作是循环遍历表单上的子输入,并为数据验证添加适当的工具提示。这发生在指令的编译部分。问题是,我在编译函数中设置的数据绑定在html中不计算。例如

app.directive('validate', ["$timeout", "$compile", "gsap", function ($timeout, $compile, gsap) {
    return {
        scope: {
            name: "@"
        },
        restrict: 'E',
        replace: true,
        controller: function ($scope) {
        $scope.validate = {};
        },
        template: '<form name="{{name}}" ng-transclude></form>',
        transclude: true,
        compile: function compile(element, attr) {
            //wrap this in a timeout function and wait for children to be available
            //Have also tried this in the postLink function to the same result
            $timeout(function () {
                var selective = element.find('.validate');
                if (selective.length > 0) {
                    $.each(selective, function (k, v) {
                        v.attr({
                            "tooltip": '{{validate.' + $(v).attr("name") + '}}',
                                "tooltip-trigger": '{{{true: "invalid", false: "valid"}[{{name}}.' + $(v).attr("name") + '.$invalid]}}'
                        });
                    });
                } else {
                    $.each(element.find('input'), function (k, v) {
                        $(v).attr({
                            "tooltip": '{{validate.' + $(v).attr("name") + '}}',
                                "tooltip-trigger": '{{{true: "invalid", false: "valid"}[{{name}}.' + $(v).attr("name") + '.$invalid]}}'
                        });
                    });
                }
            });
            return {
                post: function postLink(scope, elem, attr, controller) {

                    //...a whole bunch of validation code, all works fine...
                    //should compile with attributes and resolved databindings
                    $compile(scope, elem, attr, controller);
                }
            };
        }
    };
}]);

在我的DOM

中求值如下
<input ng-model="username" type="email" placeholder="Username" name="username" ng-required="true" ng-minlength="2" class="ng-pristine ng-invalid ng-invalid-required ng-valid-email ng-valid-minlength" required="required" tooltip="{{validate.username}}" tooltip-trigger="{{{true: &quot;invalid&quot;, false: &quot;valid&quot;}[{{name}}.username.$invalid]}}">

正如您所看到的,属性已经设置,但是数据绑定并没有像我期望的那样求值

修复。对于任何好奇的人来说,编译函数的语法是$compile(elem)(scope),我忘记了编译的作用域。