Rez*_*zen 2 javascript angularjs
我正在尝试创建一个图表指令(对现有解决方案不感兴趣).我希望使用子指令为每个条形图定义模板bartemplate.我想迭代bartemplate所以我想使用模板ng-repeat和ng-transclude将做的技巧...而角度投掷错误.
Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div ng-repeat="bar in bars track by $index" ng-transclude="" class="ng-scope">
所以你可能会问,为什么要转换?我希望能够包含我添加到图表中的任何元素(即标签),而不是干扰<bartemplate>.
您的代码有几个问题.首先,您通过在转换中进行转换来进行转换,从而使其复杂化.其次,你正在组合已经进行了转换的指令,例如ng-repeat和试图在其中转换,这是不行的.
我提供了一个简化版本的代码,可以满足您的需求:
让我试着解释它在做什么.首先,我们有barchart指令.我冒昧地简化了,但只是让整个身体充当了一个酒吧的模板而不是一个bar-template指令.
因为我们设置transclude: true了barchartdiv中的实际内容被从dom中删除,但是通过一个transclude可以通过$transclude参数注入控制器的函数可以使用.我们将此功能保存在我们的控制器上,以便我们以后可以访问它.
barchart然后该指令被该模板替换:
<div xmlns="http://www.w3.org/2000/svg">
<div ng-repeat="bar in bars track by $index" render-bar></div>
</div>
Run Code Online (Sandbox Code Playgroud)
请注意,没有ng-transclude.相反,我们创建自己的指令render-bar来渲染模板(这避免了与ng-repeat和它自己的转换的任何冲突).
该renderBar指令非常简单:
directive('renderBar', function(){
return {
require: '^barchart',
link: function(scope, element, attrs, controller){
controller.renderBarTemplate(scope, function(dom){
element.append(dom);
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
首先,我们要求有一个父barchart指令.在link函数中,我们可以获取其控制器并访问我们命名的存储的transclude函数renderBarTemplate.
我们传递的第一个参数是范围,它使函数链接到当前范围(基本上提供的范围ng-repeat使我们能够访问迭代变量,包括bar).
编译后的dom通过回调(第二个参数)返回,我们可以将其附加到<div>提供的ng-repeat.
如果您有任何疑问或需要进一步澄清,请与我们联系.
更新:
这是一个允许你遵守<bartemplate>指令的版本:
我添加了bartemplate指令:
directive('bartemplate', function(){
return {
transclude: true,
restrict: 'E',
require: '^barchart',
link: function(scope, element, attrs, barChartController, transclude){
element.remove();
barChartController.renderBarTemplate=transclude;
}
};
})
Run Code Online (Sandbox Code Playgroud)
它现在负责获取其transclude功能并将其存储在父控制器中.(因此它可以在以后被render-bar指令使用.
还要注意element.remove().这不是绝对必要的,但只是<bartemplate>从html中删除了remaning 标签.
| 归档时间: |
|
| 查看次数: |
3257 次 |
| 最近记录: |