首先,我不認爲替換:在不久的將來,真正被刪除。它已被棄用,但在任何角度1.X版本中擺脫它將是一個突破性的改變,所以我認爲你沒事,直到發佈Angular 2.0。 Angular 2.0將打破更多,所以我不會太擔心如何讓現有的應用程序工作,而不需要更換:true。很可能2.0會具有某種等效的功能,但將現有的應用程序遷移到2.0可能不是您想要做的事情。
然而,假設回答你的問題:
取代:真正做了兩兩件事:
1)替換元素與指令模板的DOM。
2)它將DOM中元素的屬性與指令模板合併。
(2)實際上是該特徵的非平凡部分,它周圍的邊緣情況是Angular團隊想要擺脫它的原因。
舉例來說,如果你的元素是:
<div some-directive ng-click="doSomething()"><div>
而且someDirective有一個模板:
<div ng-click="doSomethingInDirective()"></div>
你已經更換了節點之後的優先級? replace:true的邏輯當前會做出這些決定併爲您提供一切。
如果出於某種原因將其替換爲:真正從1.X中刪除(它不會),那麼你會怎麼做?
答案是,你將不得不手工做的替換:真正做現在,這(簡體)是:
1)獲取的原始元素的屬性
2)合併的原始元素與屬性指令模板,跟蹤不是指令和屬性的屬性,並且跟蹤每個指令的聲明位置(在原始元素或模板中)。
3)通過編譯合併的屬性指令和指令模板指令來編譯指令模板。
4)將作爲原始元素一部分的合併屬性指令鏈接到$ parent作用域,並將所有其他指令鏈接到指令作用域。鏈接指令該指令範圍
4A)如果必要的話(transclude執行transclusion:true和模板包括NG-transclude)
5)替換爲完全掛鉤指令模板原始元素。
這裏是從GitHub的相關代碼:
if (directive.replace) {
replaceDirective = directive;
if (jqLiteIsTextNode(directiveValue)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
directiveName, '');
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
// - collect directives from the template and sort them by priority
// - combine directives as: processed + template + unprocessed
var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
if (newIsolateScopeDirective) {
markDirectivesAsIsolate(templateDirectives);
}
directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
我不會出去,很快寫自己,任何時候的版本。任何需要替換的代碼:true也需要Angular 1.X,所以它會被支持。當你準備用Angular 2.0寫一個新的應用程序時,會有另一種(希望更好)的方式來做到這一點。
「標籤對瀏覽器沒有任何意義」......但不幸的是它對其他指令有意義。例如,標籤內的任何內容都不再可用於Angular的表單驗證。所以有一個堅實的用例來「替換」。 transclude是否提供相同的功能? – 2015-07-09 01:44:23
「..對瀏覽器沒有意義..」,取決於你所指的意義。我遇到了指令元素纏繞
它也不會做屬性合併,這對於我製作包裝文件輸入的組件時非常重要。 – Thayne 2016-04-29 23:44:39
相關問題