AngularJS實現(xiàn)使用路由切換視圖的方法
本文實例講述了AngularJS實現(xiàn)使用路由切換視圖的方法。分享給大家供大家參考,具體如下:
下面是一個簡單的學生信息管理實例。
注意:除了引用angular.js之外,還要引用angular-route.js。
1、創(chuàng)建index.html主視圖
在index.html主視圖中,我們將會把多個視圖共有的東西都放在里面,例如菜單。在這個例子中,我們僅僅把應用的標題放在里面,然后再用ng-view指令來告訴Angular把視圖顯示在哪兒。
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" ng-app="StuApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>學生信息</title> <script src="/Scripts/angular.min.js"></script> <script src="/Scripts/angular-route.min.js"></script> <script src="controllers.js"></script> </head> <body> <h1>學生信息</h1> <div ng-view></div> </body> </html>
2、創(chuàng)建list.html列表視圖
<table>
<tr>
<th>學號</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
</tr>
<tr ng-repeat="student in StudentList">
<td>{{student.id}}</td>
<td><a ng-href="#/view/{{student.id}}">{{student.name}}</a></td>
<td>{{student.sex}}</td>
<td>{{student.age}}</td>
</tr>
</table>
3、創(chuàng)建detail.html詳細視圖
<div>
<div><strong>學號:</strong>{{Student.id}}</div>
<div><strong>姓名:</strong>{{Student.name}}</div>
<div><strong>性別:</strong>{{Student.sex}}</div>
<div><strong>年齡:</strong>{{Student.age}}</div>
<a href="#/">返回</a>
</div>
4、創(chuàng)建controllers.js控制器腳本
//創(chuàng)建模塊
var StuServices = angular.module("StuApp", ['ngRoute']);
//在URL、模板和控制器之前建立映射關系
function StuRouteConfig($routeProvider) {
$routeProvider.when('/', {
controller: 'ListController',
templateUrl: 'list.html'
}).when('/view/:id', {
controller: 'DetailController',
templateUrl: 'detail.html'
}).otherwise({ redirectTo: '/' });
}
//配置路由,以便學生服務能夠找到它
StuServices.config(StuRouteConfig);
//一些虛擬的學生信息
StudentList = [{ id: 0, name: '張三', sex: '男', age: 18 },
{ id: 1, name: '李四', sex: '女', age: 15 },
{ id: 2, name: '王五', sex: '男', age: 16 }
];
//列表模板
StuServices.controller("ListController", function ($scope) {
$scope.StudentList = StudentList;
})
//詳細模塊:從路由信息(從URL中解析出來的)中獲取郵件id,然后用它找到正確的郵件對象
StuServices.controller("DetailController", function ($scope, $routeParams) {
$scope.Student = StudentList[$routeParams.id];
})
更多關于AngularJS相關內容感興趣的讀者可查看本站專題:《AngularJS入門與進階教程》及《AngularJS MVC架構總結》
希望本文所述對大家AngularJS程序設計有所幫助。
相關文章
Angularjs中$http以post請求通過消息體傳遞參數(shù)的實現(xiàn)方法
這篇文章主要介紹了Angularjs中$http以post請求通過消息體傳遞參數(shù)的方法,結合實例形式分析了$http使用post請求傳遞參數(shù)的相關設置與使用技巧,需要的朋友可以參考下2016-08-08
Angular項目里ngsw-config.json文件作用詳解
這篇文章主要為大家介紹了Angular項目里ngsw-config.json文件作用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
Angular6項目打包優(yōu)化的實現(xiàn)方法
這篇文章主要給大家介紹了關于Angular6項目打包優(yōu)化的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Angular6具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-12-12
AngularJS實現(xiàn)的鼠標拖動畫矩形框示例【可兼容IE8】
這篇文章主要介紹了AngularJS實現(xiàn)的鼠標拖動畫矩形框,涉及基于AngularJS的事件響應及頁面元素屬性動態(tài)操作相關實現(xiàn)技巧,需要的朋友可以參考下2019-05-05

