0

I'm stuck with dynamic template for a directive. Mainly, the directive that called as a comment.

For example, I have created a directive that should check the type of element and an appropriate template. In the link-function I check attribute type of element in the scope and select required template.

All works fine if I call directive as an attribute or an element. However, if I call it as a comment then nothing happens, the output is empty.

Here the code of that directive:

app.directive('inQux', function ($compile) {
    var template, inQux, linker;

    template = {
        foo: '<div>I\'m foo. {{item.value}}</div>',
        bar: '<div>I\'m bar. {{item.value}}</div>'
    };


    linker = function ($scope, element, attrs) {
        var content = $compile(template[$scope.item.type])($scope);

        element.append(content);
    };

    inQux = {
        restrict: 'AME',
        replace: true,
        link: linker
    };

    return inQux;
});

You can find full example by following the link

So, my question is there a way to replace content for comment-directive?

4

1 回答 1

1

如果指令作为注释,您似乎不能在指令的链接函数中使用 element.append() 。但解释很简单:无法将元素附加到注释节点。

如果您使用另一种方法(将模板直接绑定到您的指令),如下所示:

app.directive('inQux', function ($compile) {
    var inQux;

    inQux = {
        template: '<div>I\'m {{item.type}}. {{item.value}}</div>',
        restrict: 'AME',
        replace: true
    };

    return inQux;
});

...就像在这个jsfiddle中一样,它可以工作。作为额外的优势,指令的代码现在要小得多......但我不知道你想在你的原始应用程序中实现什么。

于 2013-04-24T15:15:20.063 回答