【发布时间】:2015-11-12 05:37:40
【问题描述】:
是否可以按需加载惰性和包含模块来满足另一个模块的需求?类似的东西:
var app=angular.module('myApp',[]);
app.controller('myController',['$scope',function($scope){
$scope.btnClick=function(){
(function(d,s,id){
var js, fjs= d.getElementsByTagName(s)[0];
if(d.getElementById(id)) return;
js= d.createElement(s); js.id=id;
js.onload=function(){
// do something to make myApp dependent on anotherModule,
//like if it were loaded initially: myApp=angular.module('myApp',['anotherModule']);
};
js.src='/js/anotherModule.js';
fjs.parentNode.insertBefore(js,fjs);
}(document,'script','my_id'));
}
}]);
我想在$scope.btnClick() 上使用来自'anotherModule' 的指令。
【问题讨论】:
-
你为什么要在控制器中这样做?
-
因为我希望它在用户单击按钮时加载。在大多数情况下,最初不需要加载 anotherModule.js。实际上,对我来说,在控制器内部执行它并不重要,另一种延迟加载它的方法也可能适合。
标签: angularjs module dependencies lazy-loading