Angular 不支持延迟加载作为一项功能,但任何东西仍然可以延迟加载!
关键在config
函数中:
var providers = {};
var app = angular.module('myApp', []);
app.config(function(
$controllerProvider,
$compileProvider,
$routeProvider,
$filterProvider,
$provide
) {
providers.controllerProvider = $controllerProvider;
providers.compileProvider = $compileProvider;
providers.routeProvider = $routeProvider;
providers.filterProvider = $filterProvider;
providers.provide = $provide;
});
现在您可以使用缓存的提供程序来延迟加载(注册)Angular 特性。
延迟加载控制器:
function myCtrl($scope) {
//etc
}
providers.controllerProvider.register('myCtrl', myCtrl);
延迟加载指令:
function myDirectiveName() {
//etc
}
providers.compileProvider.directive('myDirectiveName', myDirectiveName);
有关更实用和更高级的示例,请参阅我在这篇文章中的回答(单击)。我在向下滚动页面时从外部文件延迟加载视图及其控制器。
简单演示:
现场演示(点击)
<div lazy></div>
角度逻辑:
var providers = {};
var app = angular.module('myApp', []);
app.config(function(
$controllerProvider,
$compileProvider,
$routeProvider,
$filterProvider,
$provide
) {
providers.controllerProvider = $controllerProvider;
providers.compileProvider = $compileProvider;
providers.routeProvider = $routeProvider;
providers.filterProvider = $filterProvider;
providers.provide = $provide;
});
app.directive('lazy', function() {
return {
restrict: 'A',
compile: function(element, attrs) {
providers.controllerProvider.register('myCtrl', myCtrl);
providers.compileProvider.directive('myDirectiveName', myDirectiveName);
var span = angular.element('<span></span>')
.attr('my-directive-name', '')
.attr('ng-controller', 'myCtrl');
element.append(span);
}
};
});
function myDirectiveName() {
return {
restrict: 'A',
compile: function(element, attrs) {
var str = 'This text came from a lazy-loaded directive {{anotherString}}';
element.text(str);
}
};
}
function myCtrl($scope) {
$scope.anotherString = 'and this text came from a lazy-loaded controller!';
}