我是AngularJS
的新手,抱歉,如果我没有使用正确的单词来命名。
我正在尝试实施可以接受任何类型文字的directive
(包括HTML
代码和angular expressions
)。这个directive
需要处理该文本并用它做一些事情:例如,如果它在其中找到任何图像,则下载图像并用原始URL替换原始URL。
我需要“compile
”directive
的内容,因为某些图片可能位于scope
变量中(ng-src =“{{whatever}}”)。我无法知道scope
变量的名称。
我已经阅读了很多有关directives
,transclude
,共享/隔离scope
,$compile
等内容的内容,但我无法使其发挥作用我读的越多,我就越困惑。
我决定从一个简单的案例开始:一个获得简单角度表达式的指令(请注意“任何”名称可以改变):
<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,我不知道为什么'没有'的内容没有写在HTML中但是如果你看一下控制台,你会看到在compile.html()里面有角度表达式没有被替换。谢谢!
答案 0 :(得分:1)
您可以使用$interpolate
服务获取该变量的内容:
var exp = $interpolate(clone.html());
var whatever = exp(scope);
答案 1 :(得分:0)
为了在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() {
};
}
};
});
正如这个小提琴所示:http://jsfiddle.net/ur4uzrz3/