[英]How to pass directive name to template - Angular.js
I have a directive that creates a bunch of similar widgets. 我有一个指令,可以创建一堆类似的小部件。 Each widget houses and different directive. 每个小部件都有不同的指令。 Here is the template that I use to create my widget: 这是我用来创建窗口小部件的模板:
template: '<li><div {{widgetModel.directiveName}}></div></li>'
I am wanting the variables to be reconciled and or the template to declare the directive that needs to be used. 我想要协调的变量和/或模板来声明需要使用的指令。 The template will then be: 模板将是:
template: '<li><div directive-name></div></li>'
I then want it to act as a normal directive with an attribute name of directiveName
. 然后,我希望它充当具有指令名的属性名称的普通directiveName
。 This is not happening with the current code and I do not know how to make it behave like I need. 当前代码不会发生这种情况,我也不知道如何使其表现出所需的状态。 The directiveName directive can really be anything. directiveName伪指令实际上可以是任何东西。
You could do those changes at compile function: 您可以在编译功能处进行以下更改:
angular.module('myWidgets', [])
.directive('multiDirective', function() {
return {
restrict: 'E',
compile: function(element, attrs)
{
var htmlText = '<ul>' +
'<li ' + attrs.directiveName + '>' + '</li>' +
'</ul>';
element.replaceWith(htmlText);
}
}
})
And then you could call it like this: 然后可以这样称呼它:
<multi-directive directive-name='widget1' />
I made a CodePen example based on the hints in the Angular Dynamic Templates blog post that I saw referenced in another post. 我根据Angular Dynamic Templates博客文章中的提示创建了一个CodePen示例 ,我在另一篇文章中看到了这些提示。
In order to have HTML that looks like the following: 为了使HTML如下所示:
<div ng-controller="ExampleCtrl">
<div ng-repeat="dir in dirs">
<div smart />
</div>
</div>
and assuming that your controller looks something like this: 并假设您的控制器看起来像这样:
function ExampleCtrl($scope) {
$scope.dirs = ["<div dir-a />","<div dir-b />"];
}
The smart
directive could look like this: smart
指令可能如下所示:
.directive('smart', function($compile) {
return {
restrict: 'AE',
link: function (scope, element) {
element.html(scope.dir);
$compile(element.contents())(scope);
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.