【问题标题】:Angular directive with a template, does not work with z-validate带有模板的 Angular 指令,不适用于 z-validate
【发布时间】:2014-04-03 21:30:29
【问题描述】:

我正在尝试为 label:input 对创建一个指令,以在我的整个应用程序中使用。我还依靠 z-validate 属性使用 Breeze 来验证我的输入。

html 文件:

<div data-af-label-input-pair data-af-model="vm.customer.firstName">
</div>

指令:

app.directive('afLabelInputPair', function($compile) {

    var directive = {
        restrict: 'A',
        transclude: true,
        replace: true,
        scope: {                    
            afModel: '='
        },
        templateUrl: '/app/templates/af-label-input-pair.html',
        link: function (scope, element, attrs) {
            scope.opts = attrs;
            $compile(element.contents())(scope);
        }
    }

    return directive;
});

还有模板文件:

<div>
<label>Some label:</label>
<input ng-model="afModel" data-z-validate />
</div>

这是在页面上正确显示 html。但是 z-validate 并没有起作用。换句话说,我希望 z-validate 属性为我验证 vm.customer.firstName

如果我不使用指令和模板,而是直接使用html,它可以正常工作。

有人可以指点我正确的方向吗?

谢谢!

【问题讨论】:

    标签: angularjs validation templates angularjs-directive breeze


    【解决方案1】:

    我遇到了同样的问题,我通过将编译后由微风 data-z-validate 指令添加的 [span class="z-decorator"] 移动到父元素来修复它。

        // Angular directive [spaField] responsible for generating grid cell controls.
    spa.app.directive('spaField', ['$compile', function ($compile)
    {
        var directive = {
        restrict: 'A', /* Restrict this directive to attributes. */
        replace: true, /* The given element will be replaced in the link function. */
        link: function ($scope, element, attrs) {
            // The data-z-validate directive will append a [<span class="z-decorator"] to the following [input] element, by using the jquery "append" function.
            var html = '<input type="text" data-ng-model="firstName" data-z-validate>'>;
            var compiled = $compile(html)($scope);
    
            // Get the [<span class="z-decorator"] appended to the input element by the z-validate directive.
            var span = compiled[0].parentNode.children[1];
    
            // The following 2 lines will only add the input element to the DOM and not the [<span class="z-decorator"], that is added by the z-validate directive.
            element.replaceWith(compiled);
            element = compiled;
    
            // Add the [<span class="z-decorator"] to the current parent element of the input element.
            element.parent().append(span);
        }
        };
    
        return directive;
    }]);
    

    【讨论】:

      猜你喜欢
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多