當專案越來越複雜,需要控制的東西就會越來越多,因此 AngularJS 也提供了 $route 跟 view 的功能可以透過 routing 來切換不同的 view
不過有一點要注意的是,AngularJS中的 route 其實都是同一頁(SPA),所以在url的參數上會是帶在 # 之後
例如:
index.html#/ index.html#/edit index.html#/profile
基本 route 與 view 應用
首頁 index.html(使用了 BallApp Module)
View Render
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
- {{name}}
$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
Hello, {{message}}
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
- {{name}}
edit.html
Categories: AngularJS