我試圖在ng-repeat內動態地創建指令。我有一個directive-writer
,它創建了一些其他指令,但directive-writer
似乎沒有輸出指令屬性。所以第二組指令從不被渲染。ng-repeat中的AngularJS Dynamic Directives
查看this Plunker的完整演示。
總之我有這個指令標籤:
<div ng-repeat="dir in directives" directive-writer
directive-text="{{ dir.text }}" directive-type="{{ dir.directive }}"></div>
範圍數據:
$scope.directives = [
{ directive: 'one', text: 'I am One' },
{ directive: 'two', text: 'I am Two' },
{ directive: 'three', text: 'I am Three' }
];
指令定義:
.directive('directiveWriter', function() {
return {
restrict: 'A',
compile: function(tElement, tAttrs) {
tElement.html('<div say="' + tAttrs.directiveText + '" '
+ tAttrs.directiveType + '>' + tAttrs.directiveType + '</div>');
}
};
而且3個指令,所有像這樣的:
.directive('one', function() {
return {
restrict: 'A',
replace: true,
template: '<h3 class="one"></h3>',
compile: function(tElement, tAttrs) {
tElement.text('One says, ' + tAttrs.say);
}
};
問題是directiveWriter
不寫出來的tAttrs.directiveType
值只作爲文本屬性...
所以呈現的HTML是:
<div say="I am One" {{ dir.directive }} class="ng-binding">one</div>
其中,「三」是內部的渲染div作爲文本沒有問題,但永遠不會呈現爲屬性。
我不明白:
- 爲什麼文本「三」可以在div的文本中而不是作爲一個屬性的約束。
- 爲什麼該類設置爲「ng綁定」。
如此簡單卻又如此真棒! – kellycode 2016-06-01 20:25:27