當專案越來越複雜,需要控制的東西就會越來越多,因此 AngularJS 也提供了 $route 跟 view 的功能可以透過 routing 來切換不同的 view
不過有一點要注意的是,AngularJS中的 route 其實都是同一頁(SPA),所以在url的參數上會是帶在 # 之後
例如:
index.html#/ index.html#/edit index.html#/profile
基本 route 與 view 應用
首頁 index.html(使用了 BallApp Module)
<!DOCTYPE HTML>
<html ng-app="BallApp">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<!-- 使用 $route module 必須再引入 angulare-route.js -->
<script src="https://code.angularjs.org/1.2.17/angular-route.js"></script>
<script src="module.js"></script>
</head>
<body>
<h2>View Render</h2>
<!-- 使用 ng-view 屬性決定 view 載入的位置 -->
<div ng-view></div>
</body>
</html>
module.js
// 要使用$route時必須帶入ngRoute module 及 route 設定
var ballApp = angular.module('BallApp', ['ngRoute'], function($routeProvider) {
// 指定 route 及載入的 view
$routeProvider.when('/', {
templateUrl: 'view.html'
})
.when('/edit', {
templateUrl: 'edit.html'
})
// 不符合以上規則的利用 otherwise 統一導到固定的view
.otherwise({
redirectTo: '/'
});
});
// 新增 Controller
ballApp.controller('NameCtrl', function($scope) {
$scope.persons = ['Johnson', 'Febr', 'Minnine'];
});
view.html
<ul>
<li ng-repeat="name in persons">{{name}}</li>
</ul>
$route 帶入參數
module.js
var ballApp = angular.module('BallApp', ['ngRoute'], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'view.html'
})
// 使用冒號決定參數名稱
.when('/hello/:message', {
templateUrl: 'hello.html',
// 設定 view 的 controller
controller: 'HelloCtrl'
})
.otherwise({
redirectTo: '/'
});
});
// 透過 $routeParams 帶入參數
ballApp.controller('HelloCtrl', function($scope, $routeParams) {
$scope.message = $routeParams.message;
});
hello.html
<div>Hello, {{message}}</div>
URL
index.html#/hello/baby
實際應用(點擊姓名後進入修改畫面)
module.js
var ballApp = angular.module('BallApp', ['ngRoute'], function($routeProvider) {
// Route
$routeProvider.when('/', {
templateUrl: 'view.html'
})
.when('/edit/:index', {
templateUrl: 'edit.html',
controller: 'EditCtrl'
})
.otherwise({
redirectTo: '/'
});
});
// Controller
ballApp.controller('NameCtrl', function($scope) {
$scope.persons = ['Johnson', 'Febr', 'Minnine'];
}).controller('EditCtrl', function($scope, $routeParams) {
$scope.index = $routeParams.index - 1;
});
view.html
<ul ng-controller="NameCtrl">
<li ng-repeat="name in persons">
<a ng-href="#/edit/{{$index + 1}}">{{name}}</a>
</li>
</ul>
edit.html
<!-- 因為需要使用到persons陣列,因此引用NameCtrl -->
<form ng-controller="NameCtrl">
<input ng-model="persons[index]">
</form>