我正在尝试在我的应用程序中创建一个指令。但是,我需要在不同的地方使用指令,并且它们有自己的 Controller 。
所以在我的指令中
directive('test', [function($popover) {
return {
restrict: 'E',
scope: false,
link: function(scope, elem, attrs) {
}
};
}
])
如何将两个 Controller 添加到一个指令?
谢谢!
最佳答案
您可以使用name
和controller="@"
选项。
.directive('test', [function($popover) {
return {
restrict: 'E',
scope: false,
controller : "@",
name:"controller",
template:'<div>{{value}}</div>',
link: function(scope, elem, attrs) {
}
};
}
例如:-
<test controller="ctrl1"></test>
.....
<test controller="ctrl2"></test>
当您指定 controller= '@'
时,Angular 将查找具有为 中提到的元素属性指定的属性值(您可以为该属性指定任何名称)的已注册 Controller 。名称
选项。
<强> Plnkr
这是 Angular Directive(指令)实现的片段:-
if (controllerDirectives) {
....
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
controllerInstance = $controller(controller, locals);
关于javascript - 如何将 Controller 添加到指令中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25556557/