想象一个使用简单的angular UI路由的 angularjs 应用: <!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, routerProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html'
});
$urlRouterProvider.otherwise('/home');
})
.controller('MainController', function ($scope, router) {
$scope.reload = function() {
router.setUpRoutes();
};
})
;我们仅定义了一个称为 'home'的状态。如果我们需要更多的状态,只需要在 config() 增加更多的function即可。在这篇文章中,我们将会使用JSON文件方式添加更多的状态,而不是在代码中去写死。 下面是我们在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();
};
})
;我们可以看到现在正在使用 'Routing' 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();
});'Routing' 提供了一个叫做 'router' 的provider方法可以获取到JSON文件并构建各种状态。 这是一个设想的证明过程。 还有一些问题 (如果你知道怎么解决请告诉我):
你可以在我的 github 帐户上看例子。 |