我有一个复合列表指令-即-一个列表项,可以自己作为一个列表。
父指令定义了控制器:
.directive('parent', function() {
controller: function($scope) {
},
link: function (scope, element, attrs) {
}
})
该列表(由项目组成)需要父控制器本身可以正常工作(为什么不应该如此):
.directive('list', function() {
require: '^parent',
link: function (scope, element, attrs, parentCtrl) {
}
})
具体项目也是如此,这也很好:
.directive('item', function() {
require: '^parent',
link: function (scope, element, attrs, parentCtrl) {
}
})
一个项目可能是复合的,在这种情况下,它自己创建了一个“列表”。这种组合是通过$ compile(ing)链接函数中的一个列表项来完成的:
link: function (scope, element, attrs, parentCtrl) {
...
$compile("<list></list>")(scope)
...
}
这引发了一个异常:
找不到指令“ list”所需的控制器“ parent”!
原因很明显-$ compile函数未提供控制器,因此无法解决“父级”的要求。
因此,我尝试手动提供控制器:
$compile("<list></list>")(scope, null, {'parent': parentCtrl});
不会引发异常,但在需要时仍不提供此控制器。
任何想法如何使$ compile函数接受也应该评估的外部控制器?
供将来参考,以下是解决方案:
在$ compile函数上,所需的控制器可以作为已包含的控制器传递:
$compile(template)(scope, undefined, {transcludeControllers: injectedCtrl})
其中“ injectedCtrl”是列出指令期望的控制器的对象,例如if you require: '^dad'
,则transcludeControllers
如下所示:
transcludeControllers: {
dad: { //name of controller in 'require' statement
instance: vm //instance of controller
}
}
参见以下示例:https : //jsfiddle.net/qq4gqn6t/11/
而已!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句