你的位置:首页 > Java教程

[Java教程]Angularjs 路由学习笔记


从官网下载了最新版本的Angularjs 版本号:1.3.15

做一个简单的路由功能demo

首页:index.html

 1 <!DOCTYPE html > 2  3 <html> 4 <head> 5   <meta charset="utf-8" /> 6   <title>测试</title> 7   <script src="./js/angular.min.js"></script> 8   <script src="./js/angular-route.min.js"></script> 9 </head>10 <body ng-app="myApp">11   <div ng-controller="TextController">12     <p>{{someText}}</p>13   </div>14   <div ng-view></div>15 </body>16   <script>17     var myApp = angular.module('myApp', ['ngRoute']);18     myApp.controller('TextController', function ($scope) {19       $scope.someText = '测试显示内容';20     });21 22     //路由23     function emailRouteConfig($routeProvider) {24       $routeProvider.25       when('/', {26         controller: ListController,27         templateUrl: 'list.html'28       }).29       when('/view/:id', { //在id前面加一个冒号,从而制订了一个参数化URL30         controller: DetailController,31         templateUrl: 'detail.html'32       }).33       otherwise({34         redirectTo: '/'35       });36     }37 38     myApp.config(emailRouteConfig);//配置我们的路由39 40     messages = [{41       id: 0, sender: "584600034@qq.com", subject: "你好,这是一封邮件", date: "2015年4月13日", recipients: ['wifei@163.com'], message: "你好,我是xxx,这是发送给您的邮件。"42     }, {43       id: 1, sender: "584600034@qq.com", subject: "你好,这是一封邮件", date: "2015年4月13日", recipients: ['wifei@163.com'], message: "你好,我是xxx,这是发送给您的邮件。"44     }, {45       id: 2, sender: "584600034@qq.com", subject: "你好,这是一封邮件", date: "2015年4月13日", recipients: ['wifei@163.com'], message: "你好,我是xxx,这是发送给您的邮件。"46     }];47 48     function ListController($scope) {49       $scope.messages = messages;50     }51 52     function DetailController($scope,$routeParams) {53       $scope.message = messages[$routeParams.id];54     }55   </script>56 </html>

列表页:list.html

<table>  <tr>    <td><strong>发件人</strong></td>    <td><strong>内容</strong></td>    <td><strong>日期</strong></td>  </tr>  <tr ng-repeat="message in messages">    <td>{{message.sender}}</td>    <td><a href="#/view/{{message.id}}">{{message.subject}}</a></td>    <td>{{message.date}}</td>  </tr></table>

详细页:detail.html

<div><strong>项目:</strong>{{message.subject}}</div><div><strong>发送者:</strong>{{message.sender}}</div><div><strong>日期:</strong>{{message.date}}</div><div>  <strong>To:</strong>  <span ng-repeat="recipient in message.recipients">    {{recipient}}  </span></div><div>{{message.message}}</div><a href="#/">回到列表</a>

以下是此次demo的坑:

1:新版的Angularjs,引用路由功能,需要单独再引用 angular-route.js 文件

2:在定义module时也需要添加对'ngRoute'的依赖
  angular.module('xxxx', ['ngRoute'])