Angularjs 运行时动态注册指令
通常,通过使用Angularjs 运行时动态注册指令,angularjs,angularjs-directive,angularjs-module,Angularjs,Angularjs Directive,Angularjs Module,通常,通过使用指令方法在模块上注册指令: .directive('MyDirective', function (MyDep) { return { restrict: 'E', template: '<div></div>', controller: function ($scope) { } } }); .directive('MyDirective',函数(MyDep){ 返回{ 限制
指令
方法在模块上注册指令:
.directive('MyDirective', function (MyDep) {
return {
restrict: 'E',
template: '<div></div>',
controller: function ($scope) {
}
}
});
.directive('MyDirective',函数(MyDep){
返回{
限制:'E',
模板:“”,
控制器:功能($scope){
}
}
});
但是,如果我想在运行时动态注册指令,该怎么办?例如,假设用户从服务器提取以下数据:
{
directives: {
dir1: {
restrict: 'E',
template: '<div></div>',
},
dir2: {
restrict: 'E',
template: '<div></div>',
}
}
}
{
指令:{
第1条:{
限制:'E',
模板:“”,
},
第2条:{
限制:'E',
模板:“”,
}
}
}
是否有任何方法可以获取此数据并使用它为我的应用程序动态注册新指令?如果成功,我应该能够动态生成和编译依赖于它们的HTML。这是“延迟加载角度工件”问题的一个子集(我已经研究过,还有其他资源)。一种方法是使用config
函数“窃取”$compileProvider
(),然后根据您的数据按需调用$compileProvider.directive(…)
大致的想法是:
var cachedCompileProvider;
angular.module(...).config(['$compileProvider', function($compileProvider) {
cachedCompileProvider = $compileProvider;
});
然后(例如,从可以访问$http
的某个地方的内部):
(当然,您不能像上面那样从JSON响应接收控制器函数,您必须使用其他技术-但希望您能理解。)谢谢,看起来确实可以。我在问题中更正了无效的JSON(复制粘贴会对大脑造成奇怪的影响),但是编译器是否仍然允许我通过在客户端运行类似于
dirDefinition.controller=function($scope){/..}的东西来添加控制器代码>?是的,当然,dirDefinition
是一个带有控制器、链接函数等的标准指令定义对象。只是由于该格式的合理限制,您无法从JSON获取它。但是,您可以得到一个文本响应,eval
it,如果您愿意(并且对eval
感到满意),可以将其用作指令定义。很好,但是如果您首先显示列表,然后尝试注册指令,则会看到这一点。已编译的模板不会重新编译,而如果你先注册指令,然后在显示ListThreak的时候看到它在起作用,这让我的生活更轻松。
$http.get(...).then(function(response) {
angular.forEach(response.data.directives, function(dirDefinition, dirName) {
cachedCompileProvider.directive(dirName, dirDefinition);
});
});