【发布时间】:2016-06-02 10:28:57
【问题描述】:
我的控制器中有一个列表,ng-repeat 使用它来创建我的指令。在我的指令中,我使用嵌入来附加到指令的元素。
将第一项添加到我的列表时,它似乎按预期工作,但是当添加第二项时,嵌入的内容从第一项的元素中消失了。这对我来说毫无意义,所以我一定有什么误解。
我创建了一个example 来重现问题。
添加第一项后,html 看起来像预期的那样:
<div ng-controller="ctrl as c" class="ng-scope">
<test ng-repeat="item in c.items track by $index" item="item" class="ng-scope ng-isolate-scope">
<div class="ng-binding">1</div>
<span class="ng-scope">Transcluded</span>
</test>
</div>
添加第二项后,Transcluded的内容不再在第一项的元素中!
<div ng-controller="ctrl as c" class="ng-scope">
<test ng-repeat="item in c.items track by $index" item="item" class="ng-scope ng-isolate-scope">
<div class="ng-binding">1</div>
</test>
<test ng-repeat="item in c.items track by $index" item="item" class="ng-scope ng-isolate-scope">
<div class="ng-binding">2</div>
<span class="ng-scope">Transcluded</span>
</test>
</div>
HTML:
<div ng-app="ui">
<div ng-controller="ctrl as c">
<test ng-repeat="item in c.items track by $index" item="item">Transcluded</test>
</div>
</div>
打字稿:
var app = angular.module('ui', []);
class Controller {
public items = [];
constructor($timeout) {
$timeout(() => this.items.push({Id: 1}), 1000);
$timeout(() => this.items.push({Id: 2}), 2000);
}
}
app.controller('ctrl', ['$timeout', Controller]
app.directive('test', function($compile) {
return {
scope: {
item: '='
},
transclude: true,
template: "<div>{{item.Id}}</div>"
link: function(scope, element, attrs, controller, transcludeFn) {
console.log("Appending transcluded content to " + scope.item.Id)
let e = transcludeFn();
element.append(e);
}
};
});
JSFiddle:https://jsfiddle.net/rmytw9cr/2/
【问题讨论】:
-
将 ng-transclude 属性与 test 指令一起使用,它可能会开始工作...有关更多信息,请参阅 teropa.info/blog/2015/06/09/transclusion.html
标签: angularjs angularjs-directive angularjs-ng-repeat