16

有没有办法在不添加额外元素的情况下将某些内容转入指令。

例如

指示:

{
    scope: {
        someParam: "="
    },
    link: function(scope, element, attrs){
        //do something
    },
    transclude: true,
    template:'<div ng-transclude></div>'
}

源代码:

<div my-directive some-param="somethingFromController">
    my transcluded content: {{somethingElseFromController}}
</div>

在这个例子中,一个额外的 div 被添加到标记中。通常这会很好,但我试图在表格中使用这个指令,所以添加一个 div 标签搞砸了。

我也尝试不指定transcludetemplate删除额外的 div 标签,但现在{{somethingElseFromController}}找不到,因为“transcluded”内容在一个孤立的范围内。我知道我可以从链接函数中的 attrs 对象中获取我的指令的参数,而不是创建一个隔离的范围,但我宁愿避免需要使用 scope.$apply() 评估字符串。

有谁知道如何做到这一点?谢谢!

4

3 回答 3

8

@Vakey 回答的是我正在寻找的内容。

但就像今天一样,Angular 文档说:

不推荐使用传递给该compile函数的transclude函数,因为它例如不知道正确的外部范围。请改用传递给链接函数的 transclude 函数。

因此,我使用了controller(暂时)及其功能,作为$compile 文档$transclude中示例的一部分:

controller: function($scope, $element, $transclude) {
            var transcludedContent, transclusionScope;

            $transclude(function(clone, scope) {
                $element.append(clone);
                transcludedContent = clone;
                transclusionScope = scope;
            });
        },
于 2015-08-17T19:20:31.573 回答
7

This actually is possible with Angular. Directives such as ng-repeat do this. Here is how you do it:

{
    restrict: 'A',
    transclude: true,
    compile: function (tElement, attrs, transclude) {
        return function ($scope) {
            transclude($scope, function (clone) {
                tElement.append(clone);
            });
        };
    }
};

So what's going here? During linking, we are just appending the clone, which is the element we are trying to transclude, into the directive's element. Angular will apply $scope onto the clone element so you can do all the angular goodness inside that element.

于 2014-01-17T19:34:01.553 回答
4

详细说明@rob的帖子......

嵌入要求 Angular 创建一个元素,该元素是指令所在/存在的任何标签的内容的克隆……如果内容是文本,它将把它包装在一个跨度中。

这是因为它有一个 DOM 元素,可以在调用 $compile 时应用范围。

因此,基本上 transclude 添加了一个元素,原因与您不能添加的原因相同$compile('plain text here {{wee}}')

现在,您可以执行类似于您尝试使用$interpolate执行的操作,它允许您将范围应用于字符串中的绑定,例如 "blah {{foo}}"....真的不知道你想做什么,我真的不能给你一个具体的例子。

于 2013-10-17T19:51:38.247 回答