先看一個最典型的 ui-router 應用骨架:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Example</title> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script> <script src="js/app.js"></script> </head> <body ng-app="App" ng-controller="MainController"> <div ui-view></div> </body> </html>
angular.module('App', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html'
});
$urlRouterProvider.otherwise('/home');
})
.controller('MainController', function ($scope, router) {
$scope.reload = function () { router.setUpRoutes(); };
});
問題來了:狀態一多,config() 就會膨脹成一長串。與其把路由寫死在程式碼裡,不如抽到外部 JSON。
{
"xxx": { "url": "/xxx", "templateUrl": "templates/xxx.html" },
"yyy": { "url": "/yyy", "templateUrl": "templates/yyy.html" },
"zzz": { "url": "/zzz", "templateUrl": "templates/zzz.html" }
}
angular.module('App', ['ui.router', 'Routing'])
.config(function ($stateProvider, $urlRouterProvider, routerProvider) {
$stateProvider
.state('home', { url: '/home', templateUrl: 'templates/home.html' });
$urlRouterProvider.otherwise('/home');
routerProvider.setCollectionUrl('js/routeCollection.json');
})
.controller('MainController', function ($scope, router) {
$scope.reload = function () { router.setUpRoutes(); };
});
angular.module('Routing', ['ui.router'])
.provider('router', function ($stateProvider) {
var urlCollection;
this.$get = function ($http, $state) {
return {
setUpRoutes: function () {
$http.get(urlCollection).success(function (collection) {
for (var routeName in collection) {
if (!$state.get(routeName)) {
$stateProvider.state(routeName, collection[routeName]);
}
}
});
}
};
};
this.setCollectionUrl = function (url) { urlCollection = url; };
})
.run(function (router) { router.setUpRoutes(); });
關鍵是 $stateProvider.state() 可以在執行期呼叫,而不必侷限在 config 階段;$state.get() 則用來避免重複註冊。