对 AngularJS 来说非常新,我猜我正在尝试做的术语是延迟加载。我查看了几个不同的博客,但没有找到一个完全使用 AngularJS 的完整工作解决方案。
我知道如果我将<script src="js/process1.js"></script>
index.html 放入,一切正常,我正在尝试减少在初始加载时拉下的 js 数量。
由于脚本标签位于部分中,它永远不会被加载,因此永远不会创建 P1Ctrl。因此,目前,如果用户进入应用程序并且从未进入 process55,则即使从未使用过,用户仍然拥有 process55 的代码。
有没有办法在执行 process1 路由时加载文件并将在 process1.js 中创建的对象注入 main 中定义的应用程序?
索引.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Large Angular App</title>
<link rel="stylesheet" href="lib/foundation/css/foundation.min.css" />
</head>
<body ng-app="largeApp" ng-controller="LargeAppController">
<div>
<a href="#/home">Home</a> | <a href="#/process1">Process1</a>
</div>
<br/>
<br/>
<br/>
<ng-view>Test</ng-view>
<script type="text/javascript" src="lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular/angular-route.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
js/main.js:
var app = angular.module("largeApp", ['ngRoute']);
var appCtrl = app.controller("LargeAppController", function(){});
app.config(function ($routeProvider, $controllerProvider) {
// save references to the providers
app.registerCtrl = $controllerProvider.register,
$routeProvider.when('/', {templateUrl: 'partials/home.html'});
//Thinking I need to set up a resolve to fire off a script loader to load js.
$routeProvider.when('/process1', {templateUrl: 'partials/process1/process1.html'});
$routeProvider.otherwise({redirectTo: '/'});
});
部分/home.html:
<div>
Home Page
</div>
部分/process1.html:
<script type="text/javascript" src="js/process1/Process1Controller.js"></script>
Process 1 {{process1data}}
js/process1.js:
console.log("I made it here");
app.registerCtrl('Process1Controller',function($scope){
$scope.process1data = "Hello!";
}
]);