csv*_*van 3 angularjs angularjs-directive angularjs-module
通常,使用以下directive方法在模块上注册指令:
.directive('MyDirective', function (MyDep) {
return {
restrict: 'E',
template: '<div></div>',
controller: function ($scope) {
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我动态地想在运行时注册指令怎么办?例如,假设用户从服务器提取以下数据:
{
directives: {
dir1: {
restrict: 'E',
template: '<div></div>',
},
dir2: {
restrict: 'E',
template: '<div></div>',
}
}
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以把这个数据用来动态注册我的应用程序的新指令吗?如果成功,我应该能够动态生成$compile依赖于它们的HTML 和HTML.
这是"延迟加载角度工件"问题的一个子集(我在这里已经探讨过,也存在其他资源).一个想法是使用一个config函数"窃取" $compileProvider(ref),然后$compileProvider.directive(...)根据您的数据按需调用.
这个想法的草图是:
var cachedCompileProvider;
angular.module(...).config(['$compileProvider', function($compileProvider) {
cachedCompileProvider = $compileProvider;
});
Run Code Online (Sandbox Code Playgroud)
然后(例如从有权访问的内部$http):
$http.get(...).then(function(response) {
angular.forEach(response.data.directives, function(dirDefinition, dirName) {
cachedCompileProvider.directive(dirName, dirDefinition);
});
});
Run Code Online (Sandbox Code Playgroud)
(当然你不能从上面的JSON响应中接收控制器函数,你将不得不使用其他技术 - 但希望你能得到这个想法.)
| 归档时间: |
|
| 查看次数: |
1528 次 |
| 最近记录: |