angularjs - 如何使指令使用指令属性中指定的控制器?
问题描述
所以我有一个指令:
<directive data="user" templateUrl="./user.html" controller="UserController"></directive>
如上所示,我希望该指令使用“控制器”属性中指定的控制器。
AngularJS指令可以吗?或者我应该用其他方式,也许用组件?
我的代码目前如下所示:
app.directive('directive', function() {
var controllerName = "UserController"; // i want that to dynamicaly come from attribute
// check if controller extists:
var services = [];
app['_invokeQueue'].forEach(function(value){
services[value[2][0]] = true;
});
if (!services[controllerName]) controllerName = false;
return {
scope: { 'data' : '=' },
link: function (scope) {
Object.assign(scope, scope.data);
},
templateUrl: function(element, attr) {
return attr.templateurl;
},
controller: controllerName
}
});
解决方案
您可以执行以下操作(不完全按照您的要求 - 它创建了一堆嵌套范围,但应该足够了):
.directive('directive', () => {
scope: { 'data' : '=' },
template: (elem, attrs) => {
return '<div ng-controller="' + attrs.controller + ' as vm"><div ng-include="' + attrs.template + '"></div></div>';
}
});
<directive data="user" templateUrl="./user.html" controller="UserController"></directive>
- 你可以直接使用 $templateCache 而不是 ng-include
- 如果你需要控制器/模板/... 是动态的,你需要观察/观察 + dom 操作 + 重新编译东西
推荐阅读
- python - 如何使用python从文件中的当前行写入前几行
- java - 如何在 int 数组(java)中附加 int?
- photoshop-script - 在哪里可以找到有关如何使用 PhotoShop UI Toolkit 的文档?
- python - NameError:名称“年”未定义
- python - 一组顺序决策的所有可能选项组合
- azure - 使用 IIS 的云服务预热
- java - 永无止境的“Gradle 破坏了类路径”错误
- sas - 我想从 SAS 中的日期时间格式列中提取月份数据
- wordpress - Wordpress 插件无法更新:无法创建目录
- mysql - 如何在 MySQL 查询中显示非零值