多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
和我们在javaee中的顺序完全一致,我们在此的顺序仍然是配置路由,建立C层,建立V层。 # 手动创建 ## 配置路由 app/scripts/app.js 我们先删除冗余的about路由,并保存首页与默认路由.同时增加teacher路由。 ``` ... // 路由配置 .config(function($routeProvider) { $routeProvider // action = /, 控制器 = MainCtrl, 控制器别名 = main, V层模板 = views/main.html .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main' }) .when('/teacher/', { templateUrl: 'views/teacher/index.html', controller: 'TeacherIndexCtrl', controllerAs: 'teacherIndex' }) // 默认路由:如果以上条件都不符合,则跳转至'/'路由 .otherwise({ redirectTo: '/' }); }); ``` ## 建立C层 app/scripts/controllers/teacher/index.js ``` 'use strict'; /** * 教师管理,列表 */ angular.module('webAppApp') .controller('TeacherIndexCtrl', function () { console.log('success'); }); ``` ## 引用C层JS文件 建立完C层,如果想使其生效,还需要在index.html过行引用。当然了,由于about这个控制器,我们已经不需要了,所以此时还需要把引入about控制器的JS代码删除掉. app/index.html ``` <!-- build:js({.tmp,app}) scripts/scripts.js --> <script src="scripts/app.js"></script> <script src="scripts/controllers/main.js"></script> <script src="scripts/controllers/teacher/index.js"></script> <!-- endbuild --> ``` ## 建立V层 app/views/teacher/index.html ``` <table class="table"> <tr> <th>序号</th> <th>姓名</th> <th>用户名</th> <th>性别</th> <th>邮箱</th> </tr> <tr> <td>1</td> <td>张三</td> <td>zhangsan</td> <td>男</td> <td>zhangsan@yunzhiclub.com</td> </tr> <tr> <td>2</td> <td>李四</td> <td>lisi</td> <td>女</td> <td>lisi@yunzhiclub.com</td> </tr> </table> ``` ## 修改首页菜单 app/index.html ``` <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="#!/">梦云智</a> </div> <div class="collapse navbar-collapse" id="js-navbar-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#!/a">首页</a></li> <li><a ng-href="#!/teacher/">教师管理</a></li> </ul> </div> </div> ``` ## 测试 [http://localhost:9000/#!/teacher/](http://localhost:9000/#!/teacher/) ![https://box.kancloud.cn/b96e38a9c4c4a56115d8fb746fa651de_1304x554.png](https://box.kancloud.cn/b96e38a9c4c4a56115d8fb746fa651de_1304x554.png) # 自动创建 我们大概每新建一个C层,都需要经历以上的几步,那么grunt是不是可以为我们自动处理的。很遗憾,grunt也想这样做,但却被yoman捷足先登了。 我们来看看使用yoman是如何完成上述工作的。我们先恢复以上几个文件。 然后我们打开shell(以后我们说到shell时,对window平台而言,均指gitshell),并进入WebApp文件夹。然后输入: `$ yo angular:route teacher/index --uri=teacher/` > 此时,我们尽量不要关闭正在运行grunt serve的shell, 而是重新打开一个新shell. 回车确认后,让我们看看发生了什么: 1. 自动在app/scripts/app.js中添加了路由. 2. 自动创建了app/scripts/controllers/teacher/index.js,并写好了示例代码。 3. 自动创建了app/views/teacher/index.html,并写好了示例代码。 4. 自动修改了app/index.html,并为我们添加了引用的代码 我们现在需要做的,仅仅是修改app/views/teacher/index.html,然后加入我们想要的示例代码就OK了。 最后,我们去修改app/index.html关于导航部分的代码。 再点击导航中的教师管理,我们同样得到了相同的结果。但效率却得到了大幅提升。 > 官网:[https://github.com/yeoman/generator-angular#route](https://github.com/yeoman/generator-angular#route)