## 未优化的基础单页面应用
<body ng-app="myApp"> <ul> <li><a href="#/find">发现音乐</a></li> <li><a href="#/mine">我的音乐</a></li> <li><a href="#/friend">我的朋友</a></li> </ul> <div ng-view> </div> <script src="./libs/angular.js"></script> <script src="./libs/angular-route.js"></script> <script> //一个页面、一个链接对应一个路由 //module model var myApp = angular.module('myApp',['ngRoute']); //配置路由 myApp.config(['$routeProvider',function($routeProvider){ $routeProvider .when('/find',{ templateUrl:'./find.html', controller:'findController' }) .when('/mine',{ templateUrl:'./mine.html', controller:'mineController' }) .when('/friend',{ templateUrl:'./friend.html', controller:'friendController' }) }])
myApp.controller('findController',['$scope',function($scope){ $scope.title = '发现音乐'; }]) myApp.controller('mineController',['$scope',function($scope){ $scope.title = '我的音乐'; }]) myApp.controller('friendController',['$scope',function($scope){ $scope.title = '我的朋友'; }]) </script> </body>
## 项目比较大时,把所有的代码全部放在myAPP这个模块上,就可能有点多
## 创建多模块优化
var friendModule = angular.module('friendModule',[]);
friendModule.controller('friendController',['$scope',function($scope){
$scope.title = '我的朋友';
}])
var mineModule = angular.module('mineModule',[]);
mineModule.controller('mineController',['$scope',function($scope){
$scope.title = '我的音乐';
}])
var findModule = angular.module('findModule',[]);
findModule.controller('findController',['$scope',function($scope){
$scope.title = '发现音乐';
}])
## 并添加至myApp中
var myApp = angular.module('myApp',['ngRoute','friendModule','mineModule','findModule']);
## 继续优化
## 创建多个js文件分别存储各模块,例其一
var mineModule = angular.module('mineModule',[]); mineModule.config(['$routeProvider',function($routeProvider){ $routeProvider .when('/mine',{ templateUrl:'./mine.html', controller:'mineController' }) }]) mineModule.controller('mineController',['$scope',function($scope){ $scope.title = '我的音乐'; }])
## 引入各模块实现最终优化
<script src="./libs/angular.js"></script> <script src="./libs/angular-route.js"></script> <script src="./friendModule.js"></script> <script src="./mineModule.js"></script> <script src="./findModule.js"></script> <script> var myApp = angular.module('myApp',['ngRoute','friendModule','mineModule','findModule']); </script>