gpt4 book ai didi

javascript - Angular : transclude ng-repeat inside directive

转载 作者:行者123 更新时间:2023-11-29 21:57:32 24 4
gpt4 key购买 nike

我有一个指令可以嵌入原始内容,对其进行解析,并使用原始内容中的信息来帮助构建新内容。它的要点是这样的:

.directive('list', function() {
return {
restrict: 'E',
transclude: true,
templateUrl: '...',
scope: true,
controller: function($scope, $element, $attrs, $transclude) {
var items;
$transclude(function(clone) {
clone = Array.prototype.slice.call(clone);
items = clone
.filter(function(node) {
return node.nodeType === 1;
})
.map(function(node) {
return {
value: node.getAttribute('value')
text: node.innerHTML
};
});
});

// Do some stuff down here with the item information
}
}
});

然后,我这样使用它:

<list>
<item value="foo">bar</item>
<item value="baz">qux</item>
</list>

这一切都很好。当我尝试在指令内容中使用 ng-repeat 时出现问题,如下所示:

<list>
<item ng-repeat="item in items" value="{{ item.value }}">{{ item.text }}</item>
</list>

当我尝试这样做时,没有任何项目。任何人都知道为什么这行不通,或者是否有更好的方法来完成同样的事情?

最佳答案

你可以试试:

transcludeFn(scope, function (clone) {
iElem.append(clone);
})

更多细节:

HTML:

<foo data-lists='[lists data here]'>
<li ng-repeat="list in lists">{{list.name}}</li>
</foo>

指令:

var Foo = function() {
return {
restrict: 'E',
template: '...'
transclude: true,
scope: { lists: '=?' }
link: function(scope, iElem, iAttrs, Ctrl, transcludeFn) {
transcludeFn(scope, function (clone) {
iElem.append(clone);
}
}
};
};

.directive('foo', Foo);

您应该让 transcludFn 知道您将在 transcludeFn 中使用哪个范围。如果你不想使用隔离范围,你也可以尝试 transcludeFn(scope.$parent....)

关于javascript - Angular : transclude ng-repeat inside directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25641618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com