在指令中编译函数没有正确评估

时间:2014-06-09 20:29:54

标签: javascript angularjs angularjs-directive

我有一个名为validate的指令,它转换表单并根据内置的角度输入验证指令自动验证表单。该指令的一部分工作是遍历表单上的子输入并添加适当的工具提示以进行数据验证。这发生在指令的编译部分。问题是我在编译函数中设置的数据绑定不在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]}}">

正如您所看到的,属性已设置,但数据绑定未按照我的预期进行评估

1 个答案:

答案 0 :(得分:0)

修正了它。对于任何好奇的人来说,编译函数语法是$compile(elem)(scope)我忘记了编译的范围。