![](/img/trans.png)
[英]AngularJS : Isolated Scope in directive with Compile in directive
[英]AngularJS: directive with HTML and angular expressions, “compile” the contents with the outer scope
我是AngularJS
新手,很抱歉,如果我沒有使用正確的詞來命名事物。
我正在嘗試實現一個directive
,該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中沒有寫“任何”內容,但是如果您查看控制台,您會發現在compiled.html()里面的角度表達式是“取代。
謝謝!
您可以使用$interpolate
服務獲取該變量的內容:
var exp = $interpolate(clone.html());
var whatever = exp(scope);
為了在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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.