gpt4 book ai didi

javascript - 如何使用 transclude 将 ngRepeat "template"传递给 ngDirective?

转载 作者:行者123 更新时间:2023-11-29 16:12:15 25 4
gpt4 key购买 nike

演示:http://plnkr.co/edit/TiH96FCgOGnXV0suFyJA?p=preview

我有一个名为 myDirective 的 ng 指令,在指令模板中,我有一个使用 ng-repeat 打印的 li 标签列表。我想将 li 标签的内容声明为 myDirective 声明的一部分,并使用 transclude 打印所需的文本/html 内容。这样我就可以很好地分离关注点,这样我的指令就不需要知道源项的结构,调用者有责任安排 li 的内容。

类似下面的内容:

<my-directive source="vm.source">{{label}} and {{id}}</my-directive>

甚至

<my-directive source="vm.source"><a href="#{{id}}">{{label}}</a></my-directive>

ngRepeat 的模板(在 myDirective 中)看起来像

template: '<ul><li ng-repeat="item in source" ng-transclude></li></ul>',

但我无法让嵌入在 hg-repeat 中工作。我正在使用最新版本的 angular 1.2.19。准确地说,翻译有效,但我在指令级别传递的表达式无效。

请帮助并感谢堆!

我想不出更好的问题标题。欢迎您改进。

更新:我选择了@pixelbits 的答案,因为这正是我所要求的。但我实际上使用了@Norguard 的方法,因为它更有棱 Angular 。

最佳答案

嵌入的内容是针对父范围的子范围编译的(也称为嵌入范围,但这与指令的隔离范围不同)。话虽如此,您可以在父 HTML 中指定模板(尽管它有点超出 Angular 正常用例)并根据指令的独立范围手动编译它。

HTML

  <body ng-app="myApp">
<div ng-controller="myController as vm">
<my-directive source="vm.source">
<span>{{item.label}} and {{item.id}}</span>
</my-directive>
</div>
</body>

请注意,my-directive 的内部 HTML 引用必须在指令范围内定义的“item”。

指令

function directive($compile) {
return {
restrict: 'E',
scope: {
source: '='
},
compile: function(element, attr) {
// in the compile phase, remove the contents
// of element so that it is not compiled by angular.
// We will be manually compiling it in the link function.
var template = angular.element('<ul><li ng-repeat="item in source">' + element.html() + '</li></ul>');
element.empty();

// link function
return function(scope, element, attr) {
// append the template
element.append(template);

// compile and link the template against the isolated scope.
$compile(template)(scope);
}
}
};
}

Demo Plunker

关于javascript - 如何使用 transclude 将 ngRepeat "template"传递给 ngDirective?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24729019/

25 4 0