angularjs項(xiàng)目的頁(yè)面跳轉(zhuǎn)如何實(shí)現(xiàn)(5種方法)
Angular頁(yè)面?zhèn)鲄⒂卸喾N辦法,根據(jù)不同用例,我舉5種最常見(jiàn)的:
PS: 在實(shí)際項(xiàng)目中,請(qǐng)參照https://github.com/johnpapa/angular-styleguide優(yōu)化您的代碼。
1. 基于ui-router的頁(yè)面跳轉(zhuǎn)傳參
(1) 在AngularJS的app.js中用ui-router定義路由,比如現(xiàn)在有兩個(gè)頁(yè)面,一個(gè)頁(yè)面(producers.html)放置了多個(gè)producers,點(diǎn)擊其中一個(gè)目標(biāo),頁(yè)面跳轉(zhuǎn)到對(duì)應(yīng)的producer頁(yè),同時(shí)將producerId這個(gè)參數(shù)傳過(guò)去。
.state('producers', {
url: '/producers',
templateUrl: 'views/producers.html',
controller: 'ProducersCtrl'
})
.state('producer', {
url: '/producer/:producerId',
templateUrl: 'views/producer.html',
controller: 'ProducerCtrl'
})
(2) 在producers.html中,定義點(diǎn)擊事件,比如ng-click="toProducer(producerId)",在ProducersCtrl中,定義頁(yè)面跳轉(zhuǎn)函數(shù) (使用ui-router的$state.go接口):
.controller('ProducersCtrl', function ($scope, $state) {
$scope.toProducer = function (producerId) {
$state.go('producer', {producerId: producerId});
};
});
(3) 在ProducerCtrl中,通過(guò)ui-router的$stateParams獲取參數(shù)producerId,譬如:
.controller('ProducerCtrl', function ($scope, $state, $stateParams) {
var producerId = $stateParams.producerId;
});
2. 基于factory的頁(yè)面跳轉(zhuǎn)傳參
舉例:你有N個(gè)頁(yè)面,每個(gè)頁(yè)面都需要用戶填選信息,最終引導(dǎo)用戶至尾頁(yè)提交,同時(shí)后一個(gè)頁(yè)面要顯示前面所有頁(yè)面填寫(xiě)的信息。這個(gè)時(shí)候用factory傳參是比較合理的選擇(下面的代碼是一個(gè)簡(jiǎn)化版,根據(jù)需求可以不同定制):
.factory('myFactory', function () {
//定義參數(shù)對(duì)象
var myObject = {};
/**
* 定義傳遞數(shù)據(jù)的setter函數(shù)
* @param {type} xxx
* @returns {*}
* @private
*/
var _setter = function (data) {
myObject = data;
};
/**
* 定義獲取數(shù)據(jù)的getter函數(shù)
* @param {type} xxx
* @returns {*}
* @private
*/
var _getter = function () {
return myObject;
};
// Public APIs
// 在controller中通過(guò)調(diào)setter()和getter()方法可實(shí)現(xiàn)提交或獲取參數(shù)的功能
return {
setter: _setter,
getter: _getter
};
});
3. 基于factory和$rootScope.$broadcast()的傳參
(1) 舉例:在一個(gè)單頁(yè)中定義了nested views,你希望讓所有子作用域都監(jiān)聽(tīng)到某個(gè)參數(shù)的變化,并且作出相應(yīng)動(dòng)作。比如一個(gè)地圖應(yīng)用,某個(gè)$state中定義元素input,輸入地址后,地圖要定位,同時(shí)另一個(gè)狀態(tài)下的列表要顯示出該位置周邊商鋪的信息,此時(shí)多個(gè)$scope都在監(jiān)聽(tīng)地址變化。
PS: $rootScope.$broadcast()可以非常方便的設(shè)置全局事件,并讓所有子作用域都監(jiān)聽(tīng)到。
.factory('addressFactory', ['$rootScope', function ($rootScope) {
// 定義所要返回的地址對(duì)象
var address = {};
// 定義components數(shù)組,數(shù)組包括街道,城市,國(guó)家等
address.components = [];
// 定義更新地址函數(shù),通過(guò)$rootScope.$broadcast()設(shè)置全局事件'AddressUpdated'
// 所有子作用域都能監(jiān)聽(tīng)到該事件
address.updateAddress = function (value) {
this.components = angular.copy(value);
$rootScope.$broadcast('AddressUpdated');
};
// 返回地址對(duì)象
return address;
}]);
(2) 在獲取地址的controller中:
// 動(dòng)態(tài)獲取地址,接口方法省略
var component = {
addressLongName: xxxx,
addressShortName: xx,
cityLongName: xxxx,
cityShortName: xx,
countryLongName: xxxx,
countryShortName: xx,
postCode: xxxxx
};
// 定義地址數(shù)組
$scope.components = [];
$scope.$watch('components', function () {
// 將component對(duì)象推入$scope.components數(shù)組
components.push(component);
// 更新addressFactory中的components
addressFactory.updateAddress(components);
});
(3) 在監(jiān)聽(tīng)地址變化的controller中:
// 通過(guò)addressFactory中定義的全局事件'AddressUpdated'監(jiān)聽(tīng)地址變化
$scope.$on('AddressUpdated', function () {
// 監(jiān)聽(tīng)地址變化并獲取相應(yīng)數(shù)據(jù)
var street = address.components[0].addressLongName;
var city = address.components[0].cityLongName;
// 通過(guò)獲取的地址數(shù)據(jù)可以做相關(guān)操作,譬如獲取該地址周邊的商鋪,下面代碼為本人虛構(gòu)
shopFactory.getShops(street, city).then(function (data) {
if(data.status === 200){
$scope.shops = data.shops;
}else{
$log.error('對(duì)不起,獲取該位置周邊商鋪數(shù)據(jù)出錯(cuò): ', data);
}
});
});
4. 基于localStorage或sessionStorage的頁(yè)面跳轉(zhuǎn)傳參
注意事項(xiàng):通過(guò)LS或SS傳參,一定要監(jiān)聽(tīng)變量,否則參數(shù)改變時(shí),獲取變量的一端不會(huì)更新。AngularJS有一些現(xiàn)成的WebStorage dependency可以使用,譬如gsklee/ngStorage · GitHub,grevory/https://github.com/grevory/angular-local-storage。下面使用ngStorage來(lái)簡(jiǎn)述傳參過(guò)程:
(1) 上傳參數(shù)到localStorage - Controller A
// 定義并初始化localStorage中的counter屬性
$scope.$storage = $localStorage.$default({
counter: 0
});
// 假設(shè)某個(gè)factory(此例暫且命名為counterFactory)中的updateCounter()方法
// 可以用于更新參數(shù)counter
counterFactory.updateCounter().then(function (data) {
// 將新的counter值上傳到localStorage中
$scope.$storage.counter = data.counter;
});
(2) 監(jiān)聽(tīng)localStorage中的參數(shù)變化 - Controller B
$scope.counter = $localStorage.counter;
$scope.$watch('counter', function(newVal, oldVal) {
// 監(jiān)聽(tīng)變化,并獲取參數(shù)的最新值
$log.log('newVal: ', newVal);
});
5. 基于localStorage/sessionStorage和Factory的頁(yè)面?zhèn)鲄?/strong>
由于傳參出現(xiàn)的不同的需求,將不同方式組合起來(lái)可幫助你構(gòu)建低耦合便于擴(kuò)展和維護(hù)的代碼。
舉例:應(yīng)用的Authentication(授權(quán))。用戶登錄后,后端傳回一個(gè)時(shí)限性的token,該用戶下次訪問(wèn)應(yīng)用,通過(guò)檢測(cè)token和相關(guān)參數(shù),可獲取用戶權(quán)限,因而無(wú)須再次登錄即可進(jìn)入相應(yīng)頁(yè)面(Automatically Login)。其次所有的APIs都需要在HTTP header里注入token才能與服務(wù)器傳輸數(shù)據(jù)。此時(shí)我們看到token扮演一個(gè)重要角色:(a)用于檢測(cè)用戶權(quán)限,(b)保證前后端數(shù)據(jù)傳輸安全性。以下實(shí)例中使用GitHub - gsklee/ngStorage: localStorage and sessionStorage done right for AngularJS.和GitHub - Narzerus/angular-permission: Simple route authorization via roles/permissions。
(1)定義一個(gè)名為auth.service.js的factory,用于處理和authentication相關(guān)的業(yè)務(wù)邏輯,比如login,logout,checkAuthentication,getAuthenticationParams等。此處略去其他業(yè)務(wù),只專注Authentication的部分。
(function() {
'use strict';
angular
.module('myApp')
.factory('authService', authService);
/** @ngInject */
function authService($http, $log, $q, $localStorage, PermissionStore, ENV) {
var apiUserPermission = ENV.baseUrl + 'user/permission';
var authServices = {
login: login,
logout: logout,
getAuthenticationParams: getAuthenticationParams,
checkAuthentication: checkAuthentication
};
return authServices;
////////////////
/**
* 定義處理錯(cuò)誤函數(shù),私有函數(shù)。
* @param {type} xxx
* @returns {*}
* @private
*/
function handleError(name, error) {
return $log.error('XHR Failed for ' + name + '.\n', angular.toJson(error, true));
}
/**
* 定義login函數(shù),公有函數(shù)。
* 若登錄成功,把服務(wù)器返回的token存入localStorage。
* @param {type} xxx
* @returns {*}
* @public
*/
function login(loginData) {
var apiLoginUrl = ENV.baseUrl + 'user/login';
return $http({
method: 'POST',
url: apiLoginUrl,
params: {
username: loginData.username,
password: loginData.password
}
})
.then(loginComplete)
.catch(loginFailed);
function loginComplete(response) {
if (response.status === 200 && _.includes(response.data.authorities, 'admin')) {
// 將token存入localStorage。
$localStorage.authtoken = response.headers().authtoken;
setAuthenticationParams(true);
} else {
$localStorage.authtoken = '';
setAuthenticationParams(false);
}
}
function loginFailed(error) {
handleError('login()', error);
}
}
/**
* 定義logout函數(shù),公有函數(shù)。
* 清除localStorage和PermissionStore中的數(shù)據(jù)。
* @public
*/
function logout() {
$localStorage.$reset();
PermissionStore.clearStore();
}
/**
* 定義傳遞數(shù)據(jù)的setter函數(shù),私有函數(shù)。
* 用于設(shè)置isAuth參數(shù)。
* @param {type} xxx
* @returns {*}
* @private
*/
function setAuthenticationParams(param) {
$localStorage.isAuth = param;
}
/**
* 定義獲取數(shù)據(jù)的getter函數(shù),公有函數(shù)。
* 用于獲取isAuth和token參數(shù)。
* 通過(guò)setter和getter函數(shù),可以避免使用第四種方法所提到的$watch變量。
* @param {type} xxx
* @returns {*}
* @public
*/
function getAuthenticationParams() {
var authParams = {
isAuth: $localStorage.isAuth,
authtoken: $localStorage.authtoken
};
return authParams;
}
/*
* 第一步: 檢測(cè)token是否有效.
* 若token有效,進(jìn)入第二步。
*
* 第二步: 檢測(cè)用戶是否依舊屬于admin權(quán)限.
*
* 只有滿足上述兩個(gè)條件,函數(shù)才會(huì)返回true,否則返回false。
* 請(qǐng)參看angular-permission文檔了解其工作原理https://github.com/Narzerus/angular-permission/wiki/Managing-permissions
*/
function checkAuthentication() {
var deferred = $q.defer();
$http.get(apiUserPermission).success(function(response) {
if (_.includes(response.authorities, 'admin')) {
deferred.resolve(true);
} else {
deferred.reject(false);
}
}).error(function(error) {
handleError('checkAuthentication()', error);
deferred.reject(false);
});
return deferred.promise;
}
}
})();
(2)定義名為index.run.js的文件,用于在應(yīng)用載入時(shí)自動(dòng)運(yùn)行權(quán)限檢測(cè)代碼。
(function() {
'use strict';
angular
.module('myApp')
.run(checkPermission);
/** @ngInject */
/**
* angular-permission version 3.0.x.
* https://github.com/Narzerus/angular-permission/wiki/Managing-permissions.
*
* 第一步: 運(yùn)行authService.getAuthenticationParams()函數(shù).
* 返回true:用戶之前成功登陸過(guò)。因而localStorage中已儲(chǔ)存isAuth和authtoken兩個(gè)參數(shù)。
* 返回false:用戶或許已logout,或是首次訪問(wèn)應(yīng)用。因而強(qiáng)制用戶至登錄頁(yè)輸入用戶名密碼登錄。
*
* 第二步: 運(yùn)行authService.checkAuthentication()函數(shù).
* 返回true:用戶的token依舊有效,同時(shí)用戶依然擁有admin權(quán)限。因而無(wú)需手動(dòng)登錄,頁(yè)面將自動(dòng)重定向到admin頁(yè)面。
* 返回false:要么用戶token已經(jīng)過(guò)期,或用戶不再屬于admin權(quán)限。因而強(qiáng)制用戶至登錄頁(yè)輸入用戶名密碼登錄。
*/
function checkPermission(PermissionStore, authService) {
PermissionStore
.definePermission('ADMIN', function() {
var authParams = authService.getAuthenticationParams();
if (authParams.isAuth) {
return authService.checkAuthentication();
} else {
return false;
}
});
}
})();
(3)定義名為authInterceptor.service.js的文件,用于在所有該應(yīng)用請(qǐng)求的HTTP requests的header中注入token。關(guān)于AngularJS的Interceptor,請(qǐng)參看AngularJS。
(function() {
'use strict';
angular
.module('myApp')
.factory('authInterceptorService', authInterceptorService);
/** @ngInject */
function authInterceptorService($q, $injector, $location) {
var authService = $injector.get('authService');
var authInterceptorServices = {
request: request,
responseError: responseError
};
return authInterceptorServices;
////////////////
// 將token注入所有HTTP requests的headers。
function request(config) {
var authParams = authService.getAuthenticationParams();
config.headers = config.headers || {};
if (authParams.authtoken) config.headers.authtoken = authParams.authtoken;
return config || $q.when(config);
}
function responseError(rejection) {
if (rejection.status === 401) {
authService.logout();
$location.path('/login');
}
return $q.reject(rejection);
}
}
})();
自己總結(jié);(1)ng-click = "isShow"; $sope.isShow = true; (2)配置路由;(3)使用$location.urle(./mainchat/message.html);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- AngularJS利用Controller完成URL跳轉(zhuǎn)
- AngularJS路由實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)實(shí)例
- Angular 頁(yè)面跳轉(zhuǎn)時(shí)傳參問(wèn)題
- Angular中$state.go頁(yè)面跳轉(zhuǎn)并傳遞參數(shù)的方法
- AngularJS之頁(yè)面跳轉(zhuǎn)Route實(shí)例代碼
- angular4 如何在全局設(shè)置路由跳轉(zhuǎn)動(dòng)畫(huà)的方法
- AngularJS實(shí)現(xiàn)單一頁(yè)面內(nèi)設(shè)置跳轉(zhuǎn)路由的方法
- AngularJS頁(yè)面帶參跳轉(zhuǎn)及參數(shù)解析操作示例
- AngularJS實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)后自動(dòng)彈出對(duì)話框?qū)嵗a
- AngularJS實(shí)現(xiàn)的錨點(diǎn)樓層跳轉(zhuǎn)功能示例
相關(guān)文章
利用Angularjs中模塊ui-route管理狀態(tài)的方法
這篇文章主要給大家介紹了如何用Angularjs中的模板ui-route來(lái)管理狀態(tài)的方法,文中通過(guò)示例代碼介紹的很詳細(xì),相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,有需要的朋友可以一起來(lái)學(xué)習(xí)學(xué)習(xí)。2016-12-12
實(shí)例詳解angularjs和ajax的結(jié)合使用
本篇文章給大家介紹angularjs和ajax的結(jié)合使用,本文介紹的非常詳細(xì),對(duì)angularjs和ajax感興趣的朋友一起參考下吧2015-10-10
angular強(qiáng)制更新ui視圖的實(shí)現(xiàn)方法
這篇文章主要介紹了angular強(qiáng)制更新ui視圖的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
AngularJS 輸入驗(yàn)證詳解及實(shí)例代碼
本文主要介紹AngularJS 輸入驗(yàn)證,這里對(duì)AngularJS 輸入驗(yàn)證的資料做了整理,并附簡(jiǎn)單實(shí)例代碼和效果圖,有需要的小伙伴參考下2016-07-07
angularjs指令中的compile與link函數(shù)詳解
這篇文章主要介紹了angularjs指令中的compile與link函數(shù)詳解,本文同時(shí)訴大家complie,pre-link,post-link的用法與區(qū)別等內(nèi)容,需要的朋友可以參考下2014-12-12
詳解AngularJS臟檢查機(jī)制及$timeout的妙用
本篇文章主要介紹了詳解AngularJS臟檢查機(jī)制及$timeout的妙用,“臟檢查”是Angular中的核心機(jī)制之一,它是實(shí)現(xiàn)雙向綁定、MVVM模式的重要基礎(chǔ),有興趣的可以了解一下2017-06-06

