我试图将对象数组传递给指令,在指令内部使用 ngRepeat 在嵌入的 html 中输出传递的项目。这本质上与讨论的问题相同here .
我尝试了一些不同的方法,使用编译和链接功能,但我想我无法集中注意力在范围界定上。 petebacondarwin 建议的解决方案 - here确实有效,但我需要(想要)将数组传递给指令。
这是我当前的版本 - Plunker
指令
(function() {
"use strict";
function MyDirective() {
return {
restrict: "E",
scope: {
items: "="
},
link: function link(scope, element, attrs) {
var children = element.children();
var template = angular.element('<div class="item" ng-repeat="item in items"></div>');
template.append(children);
var wrapper = angular.element('<div class="list"></div>');
wrapper.append(template);
element.html('');
element.append(wrapper);
}
};
}
angular
.module("app.MyDirective", [])
.directive("myDirective", [MyDirective]);
}());
html
<my-directive items="main.items">
<h1>{{item.title}}</h1>
<p>{{item.content}}</p>
</my-directive>
谢谢
最佳答案
指令内的代码未编译,因此对 Angular 来说“不可见”。这是由于代码没有嵌入,而是在指令中被删除和替换造成的。
为了“使其对 Angular 可见”,您应该在 link
末尾添加这行代码:
$compile(wrapper)(scope);
这将获取新的代码包装器,对其进行编译并将其链接到范围
更新了plunkr:
关于javascript - AngularJS : ngRepeat in Directive with transcluded content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27168650/