AngularJS:带有 HTML 和 angular 表达式的指令,"compile" 具有外部作用域的内容

AngularJS: directive with HTML and angular expressions, "compile" the contents with the outer scope

我是 AngularJS 的新手,抱歉,如果我没有使用正确的词来命名事物。

我正在尝试实现一个可以接受任何类型的文本(包括 HTML 标签和 angular expressions)的 directive。这个 directive 需要处理该文本并用它做一些事情:例如,如果它在其中找到任何图像,则下载该图像并将原始 URL 替换为本地 URL.

我需要“compiledirective 的内容,因为某些图像可能在 scope 变量中 (ng-src="{{whatever}}")。我不知道 scope 变量的名称。

我已经阅读了很多关于 directivestransclude、shared/isolated scope$compile 等的内容,但我不能让它工作,我读得越多,我就越困惑。

我决定从一个简单的案例开始:一个获取简单 angular 表达式的指令(请注意 'whatever' 名称可以更改):

<format-text>{{whatever}}</format-text>

我想获取指令内 'whatever' 变量内的文本。我尝试了很多东西,但无法正常工作。这是我的最新测试:

angular.module('mymodule').directive('formatText', function($compile) {

     return {
        restrict: 'E',
        scope: true,
        transclude: true,
        link: function(scope, element, attrs, ctrl, transclude) {
            transclude(scope, function(clone, outerScope) {
                var template = '<span>'+clone.html()+'</span>';
                var compiled = $compile(template)(outerScope);
                console.log(compiled.html());
            });
        }
    };
});

该指令在控制台中写入以下内容:

{{whatever}}

我想获取变量的内容。变量 'whatever' 在作用域中定义,并且在视图中解析正常。

有人知道我怎样才能实现我想要做的事情吗?

编辑:我为它创建了一个 jsfiddle,我不知道为什么 'whatever' 内容没有写在 HTML 中,但是如果您查看控制台,您会看到在 compiled.html() 中,angular 表达式未被替换。

http://jsfiddle.net/8ngcwxen/

谢谢!

为了在 Angular 处理指令之前更改指令的模板,您必须使用 compile 函数。一个简单的例子是将内容作为文本获取,清空内容,运行 在文本中进行转换并将转换后的文本设置回去,例如:

app.directive('formatText', function() {
    return {
        restrict: 'E',
        scope: false,
        compile: function(tElem, tAttrs) {
            var html = tElem.html();

            tElem.empty();

            tElem.html(processTemplateText(html));

            return function() {
            };
        }
    };
});

如本 fiddle 所示:http://jsfiddle.net/ur4uzrz3/

您可以使用 $interpolate 服务获取该变量的内容:

var exp = $interpolate(clone.html());
var whatever = exp(scope);