1、基於ui-router的頁面跳轉傳參
(1) 用ui-router定義路由,比如有兩個頁面,一個頁面(producers.html)放置了多個producers,點擊其中一個目標,頁面跳轉到對應的producer頁面,同時將producerId這個參數傳過去。
.state('producers',{ url: '/producers', templateUrl: 'views/producers.html', controller: 'ProducersCtrl' }) .state('producers',{ url: '/producer/:producerId', templateUrl: 'views/producer.html', controller: 'ProducerCtrl' })
(2)在producer.html中,定義點擊事件,比如ng-click="toProducer(producerId)", 在ProducersCtrl中,定義頁面跳轉函數(使用ui-router的$state.go接口):
.controller('ProducersCtrl', function ($scope, $state) { $scope.toProducer = function (producerId) { $state.go('producer', {producerId: producerId}); }; });
(3)在ProducerCtrl中,通過ui-router的$stateParams獲取參數producerId,
.controller('ProducerCtrl', function($scope, $state, $stateParams){ var producerId = $stateParams.producerId; });
2、基於factory的頁面跳轉傳參
舉例:有N個頁面,每個頁面都需要用戶填選信息,最終引導用戶至尾頁提交,同時后一個頁面要顯示前面所有頁面填寫的信息。這時用factory傳參是比較合理的選擇
1 .factory('myFactory', function () { 2 //定義參數對象 3 var myObject = {}; 4 5 /** 6 * 定義傳遞數據的setter函數 7 * @param {type} xxx 8 * @returns {*} 9 * @private 10 */ 11 var _setter = function (data) { 12 myObject = data; 13 }; 14 15 /** 16 * 定義獲取數據的getter函數 17 * @param {type} xxx 18 * @returns {*} 19 * @private 20 */ 21 var _getter = function () { 22 return myObject; 23 }; 24 25 // Public APIs 26 // 在controller中通過調setter()和getter()方法可實現提交或獲取參數的功能 27 return { 28 setter: _setter, 29 getter: _getter 30 }; 31 });
3、基於factory和$rootScope.$broadcast()的傳參
(1)舉例:
PS: $rootScope.$broadcast()可以非常方便的設置全局事件,並讓所有子作用域都監聽到。
.factory('addressFactory', ['$rootScope', function ($rootScope) { // 定義所要返回的地址對象 var address = {}; // 定義components數組,數組包括街道,城市,國家等 address.components = []; // 定義更新地址函數,通過$rootScope.$broadcast()設置全局事件'AddressUpdated' // 所有子作用域都能監聽到該事件 address.updateAddress = function (value) { this.components = angular.copy(value); $rootScope.$broadcast('AddressUpdated'); }; // 返回地址對象 return address; }]);
(2)在獲取地址的controller中:
// 動態獲取地址,接口方法省略 var component = { addressLongName: xxxx, addressShortName: xx, cityLongName: xxxx, cityShortName: xx, countryLongName: xxxx, countryShortName: xx, postCode: xxxxx }; // 定義地址數組 $scope.components = []; $scope.$watch('components', function () { // 將component對象推入$scope.components數組 components.push(component); // 更新addressFactory中的components addressFactory.updateAddress(components); });
(3)在監聽地址變化的controller中:
// 通過addressFactory中定義的全局事件'AddressUpdated'監聽地址變化 $scope.$on('AddressUpdated', function () { // 監聽地址變化並獲取相應數據 var street = address.components[0].addressLongName; var city = address.components[0].cityLongName; // 通過獲取的地址數據可以做相關操作,譬如獲取該地址周邊的商鋪,下面代碼為本人虛構 shopFactory.getShops(street, city).then(function (data) { if(data.status === 200){ $scope.shops = data.shops; }else{ $log.error('對不起,獲取該位置周邊商鋪數據出錯: ', data); } }); });
4. 基於localStorage或sessionStorage的頁面跳轉傳參
(1) 上傳參數到localStorage - Controller A
// 定義並初始化localStorage中的counter屬性 $scope.$storage = $localStorage.$default({ counter: 0 }); // 假設某個factory(此例暫且命名為counterFactory)中的updateCounter()方法 // 可以用於更新參數counter counterFactory.updateCounter().then(function (data) { // 將新的counter值上傳到localStorage中 $scope.$storage.counter = data.counter; });
(2)監聽localStorage中的參數變化 - Controller B
$scope.counter = $localStorage.counter; $scope.$watch('counter', function(newVal, oldVal) { // 監聽變化,並獲取參數的最新值 $log.log('newVal: ', newVal); });
5. 基於localStorage/sessionStorage和Factory的頁面傳參
舉例:應用的Authentication(授權)。用戶登錄后,后端傳回一個時限性的token,該用戶下次訪問應用,通過檢測token和相關參數,可獲取用戶權限,因而無須再次登錄即可進入相應頁面(Automatically Login)。其次所有的APIs都需要在HTTP header里注入token才能與服務器傳輸數據。此時我們看到token扮演一個重要角色:(a)用於檢測用戶權限,(b)保證前后端數據傳輸安全性。以下實例中使用 GitHub - gsklee/ngStorage: localStorage and sessionStorage done right for AngularJS.和 GitHub - Narzerus/angular-permission: Simple route authorization via roles/permissions。
(1)定義一個名為auth.service.js的factory,用於處理和authentication相關的業務邏輯,比如login,logout,checkAuthentication,getAuthenticationParams等。此處略去其他業務,只專注Authentication的部分。
1 (function() { 2 'use strict'; 3 4 angular 5 .module('myApp') 6 .factory('authService', authService); 7 8 /** @ngInject */ 9 function authService($http, $log, $q, $localStorage, PermissionStore, ENV) { 10 var apiUserPermission = ENV.baseUrl + 'user/permission'; 11 12 var authServices = { 13 login: login, 14 logout: logout, 15 getAuthenticationParams: getAuthenticationParams, 16 checkAuthentication: checkAuthentication 17 }; 18 19 return authServices; 20 21 //////////////// 22 23 /** 24 * 定義處理錯誤函數,私有函數。 25 * @param {type} xxx 26 * @returns {*} 27 * @private 28 */ 29 function handleError(name, error) { 30 return $log.error('XHR Failed for ' + name + '.\n', angular.toJson(error, true)); 31 } 32 33 /** 34 * 定義login函數,公有函數。 35 * 若登錄成功,把服務器返回的token存入localStorage。 36 * @param {type} xxx 37 * @returns {*} 38 * @public 39 */ 40 function login(loginData) { 41 var apiLoginUrl = ENV.baseUrl + 'user/login'; 42 43 return $http({ 44 method: 'POST', 45 url: apiLoginUrl, 46 params: { 47 username: loginData.username, 48 password: loginData.password 49 } 50 }) 51 .then(loginComplete) 52 .catch(loginFailed); 53 54 function loginComplete(response) { 55 if (response.status === 200 && _.includes(response.data.authorities, 'admin')) { 56 // 將token存入localStorage。 57 $localStorage.authtoken = response.headers().authtoken; 58 setAuthenticationParams(true); 59 } else { 60 $localStorage.authtoken = ''; 61 setAuthenticationParams(false); 62 } 63 } 64 65 function loginFailed(error) { 66 handleError('login()', error); 67 } 68 } 69 70 /** 71 * 定義logout函數,公有函數。 72 * 清除localStorage和PermissionStore中的數據。 73 * @public 74 */ 75 function logout() { 76 $localStorage.$reset(); 77 PermissionStore.clearStore(); 78 } 79 80 /** 81 * 定義傳遞數據的setter函數,私有函數。 82 * 用於設置isAuth參數。 83 * @param {type} xxx 84 * @returns {*} 85 * @private 86 */ 87 function setAuthenticationParams(param) { 88 $localStorage.isAuth = param; 89 } 90 91 /** 92 * 定義獲取數據的getter函數,公有函數。 93 * 用於獲取isAuth和token參數。 94 * 通過setter和getter函數,可以避免使用第四種方法所提到的$watch變量。 95 * @param {type} xxx 96 * @returns {*} 97 * @public 98 */ 99 function getAuthenticationParams() { 100 var authParams = { 101 isAuth: $localStorage.isAuth, 102 authtoken: $localStorage.authtoken 103 }; 104 return authParams; 105 } 106 107 /* 108 * 第一步: 檢測token是否有效. 109 * 若token有效,進入第二步。 110 * 111 * 第二步: 檢測用戶是否依舊屬於admin權限. 112 * 113 * 只有滿足上述兩個條件,函數才會返回true,否則返回false。 114 * 請參看angular-permission文檔了解其工作原理https://github.com/Narzerus/angular-permission/wiki/Managing-permissions 115 */ 116 function checkAuthentication() { 117 var deferred = $q.defer(); 118 119 $http.get(apiUserPermission).success(function(response) { 120 if (_.includes(response.authorities, 'admin')) { 121 deferred.resolve(true); 122 } else { 123 deferred.reject(false); 124 } 125 }).error(function(error) { 126 handleError('checkAuthentication()', error); 127 deferred.reject(false); 128 }); 129 130 return deferred.promise; 131 } 132 } 133 })();
(2)定義名為index.run.js的文件,用於在應用載入時自動運行權限檢測代碼。
1 (function() { 2 'use strict'; 3 4 angular 5 .module('myApp') 6 .run(checkPermission); 7 8 /** @ngInject */ 9 10 /** 11 * angular-permission version 3.0.x. 12 * https://github.com/Narzerus/angular-permission/wiki/Managing-permissions. 13 * 14 * 第一步: 運行authService.getAuthenticationParams()函數. 15 * 返回true:用戶之前成功登陸過。因而localStorage中已儲存isAuth和authtoken兩個參數。 16 * 返回false:用戶或許已logout,或是首次訪問應用。因而強制用戶至登錄頁輸入用戶名密碼登錄。 17 * 18 * 第二步: 運行authService.checkAuthentication()函數. 19 * 返回true:用戶的token依舊有效,同時用戶依然擁有admin權限。因而無需手動登錄,頁面將自動重定向到admin頁面。 20 * 返回false:要么用戶token已經過期,或用戶不再屬於admin權限。因而強制用戶至登錄頁輸入用戶名密碼登錄。 21 */ 22 function checkPermission(PermissionStore, authService) { 23 PermissionStore 24 .definePermission('ADMIN', function() { 25 var authParams = authService.getAuthenticationParams(); 26 if (authParams.isAuth) { 27 return authService.checkAuthentication(); 28 } else { 29 return false; 30 } 31 }); 32 } 33 })();
(3)定義名為authInterceptor.service.js的文件,用於在所有該應用請求的HTTP requests的header中注入token。關於AngularJS的Interceptor,請參看AngularJS。
1 (function() { 2 'use strict'; 3 4 angular 5 .module('myApp') 6 .factory('authInterceptorService', authInterceptorService); 7 8 /** @ngInject */ 9 function authInterceptorService($q, $injector, $location) { 10 var authService = $injector.get('authService'); 11 12 var authInterceptorServices = { 13 request: request, 14 responseError: responseError 15 }; 16 17 return authInterceptorServices; 18 19 //////////////// 20 21 // 將token注入所有HTTP requests的headers。 22 function request(config) { 23 var authParams = authService.getAuthenticationParams(); 24 config.headers = config.headers || {}; 25 if (authParams.authtoken) config.headers.authtoken = authParams.authtoken; 26 27 return config || $q.when(config); 28 } 29 30 function responseError(rejection) { 31 if (rejection.status === 401) { 32 authService.logout(); 33 $location.path('/login'); 34 } 35 return $q.reject(rejection); 36 } 37 } 38 })();
轉自知乎:https://www.zhihu.com/question/33565135