想象一个使用简单的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文件方式添加更多的状态,而不是在代码中去写死。Linux下JSON库的编译及代码测试 http://www.linuxidc.com/Linux/2013-03/81607.htmjQuery 获取JSON数据[$.getJSON方法] http://www.linuxidc.com/Linux/2013-03/81673.htm用jQuery以及JSON包将表单数据转为JSON字符串 http://www.linuxidc.com/Linux/2013-01/77560.htm下面是我们在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文件并构建各种状态。这是一个设想的证明过程。还有一些问题 (如果你知道怎么解决请告诉我):
- 直到我们从一个http请求加载了各种状态为止, angular 应用在加载的时候没有得到所有的状态, 所以我们要使用老的方式至少加载第一个状态。
- 我们可以在应用运行的时候重新加载状态。我们可以新加状态,但是我们没法改变已经存的的状态。
你可以在我的 github 帐户上看例子。
带你走近AngularJS系列:
- 带你走近AngularJS - 基本功能介绍 http://www.linuxidc.com/Linux/2014-05/102140.htm
- 带你走近AngularJS - 体验指令实例 http://www.linuxidc.com/Linux/2014-05/102141.htm
- 带你走近AngularJS - 创建自定义指令 http://www.linuxidc.com/Linux/2014-05/102142.htm
如何在 AngularJS 中对控制器进行单元测试 http://www.linuxidc.com/Linux/2013-12/94166.htmAngularJS 之 Factory vs Service vs Provider http://www.linuxidc.com/Linux/2014-05/101475.htm
AngularJS 的详细介绍:请点这里
AngularJS 的下载地址:请点这里
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-07/104083.htm