Angularjs製作簡單的路由功能簡單程式碼例項

admin發表於2017-04-05

從官網下載了最新版本的Angularjs 版本號:1.3.15

首頁:index.html

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script src="./js/angular.min.js"></script>
<script src="./js/angular-route.min.js"></script>
</head>
<body ng-app="myApp">
  <div ng-controller="TextController">
     <p>{{someText}}</p>
  </div>
  <div ng-view></div>
</body>
  <script>
    var myApp = angular.module('myApp', ['ngRoute']);
    myApp.controller('TextController', function ($scope) {
      $scope.someText = '測試顯示內容';
    });
  
    //路由
    function emailRouteConfig($routeProvider) {
      $routeProvider.
      when('/', {
        controller: ListController,
        templateUrl: 'list.html'
      }).
      when('/view/:id', { //在id前面加一個冒號,從而制訂了一個引數化URL
        controller: DetailController,
        templateUrl: 'detail.html'
      }).
      otherwise({
        redirectTo: '/'
      });
    }
  
    myApp.config(emailRouteConfig);//配置我們的路由
  
    messages = [{
      id: 0, sender: "123456@qq.com", subject: "你好,這是一封郵件", date: "2015年4月13日", recipients: ['wifei@163.com'], message: "你好,我是xxx,這是傳送給您的郵件。"
    }, {
      id: 1, sender: "123456@qq.com", subject: "你好,這是一封郵件", date: "2015年4月13日", recipients: ['wifei@163.com'], message: "你好,我是xxx,這是傳送給您的郵件。"
    }, {
      id: 2, sender: "123456@qq.com", subject: "你好,這是一封郵件", date: "2015年4月13日", recipients: ['wifei@163.com'], message: "你好,我是xxx,這是傳送給您的郵件。"
    }];
  
    function ListController($scope) {
      $scope.messages = messages;
    }
  
    function DetailController($scope,$routeParams) {
      $scope.message = messages[$routeParams.id];
    }
  </script>
</html>

列表頁:list.html

[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

[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>

1:新版的Angularjs,引用路由功能,需要單獨再引用 angular-route.js 檔案

2:在定義module時也需要新增對'ngRoute'的依賴angular.module('xxxx', ['ngRoute'])

相關文章