Demo: http://plnkr.co/edit/TiH96FCgOGnXV0suFyJA?p=preview http://plnkr.co/edit/TiH96FCgOGnXV0suFyJA?p=preview
我有一个名为 myDirective 的 ng 指令,在指令模板中我有一个使用 ng-repeat 打印的 li 标签列表。我想将 li 标签的内容声明为 myDirective 声明的一部分,并使用 transinclude 打印所需的文本/html 内容。这样我就可以很好地分离关注点,这样我的指令就不需要知道源项的结构,并且调用者有责任布局 li 的内容。
像下面这样:
<my-directive source="vm.source">{{label}} and {{id}}</my-directive>
or even
<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 的方法,因为它是更有角度的方式。
嵌入的内容是针对父作用域的子作用域(也称为嵌入作用域,但这与指令的隔离作用域不同)进行编译的。话虽这么说,您可以在父 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);
}
}
};
}
演示插件 http://plnkr.co/edit/QrnkOouAjbmNSg8BPOB5?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)