溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

angularjs項目中實現(xiàn)頁面跳轉(zhuǎn)的方法

發(fā)布時間:2021-02-22 10:29:29 來源:億速云 閱讀:451 作者:小新 欄目:web開發(fā)

這篇文章主要介紹angularjs項目中實現(xiàn)頁面跳轉(zhuǎn)的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

1. 基于ui-router的頁面跳轉(zhuǎn)傳參

(1) 在AngularJS的app.js中用ui-router定義路由,比如現(xiàn)在有兩個頁面,一個頁面(producers.html)放置了多個producers,點擊其中一個目標,頁面跳轉(zhuǎn)到對應的producer頁,同時將producerId這個參數(shù)傳過去。

.state('producers', {
  url: '/producers',
  templateUrl: 'views/producers.html',
  controller: 'ProducersCtrl'
})
.state('producer', {
  url: '/producer/:producerId',
  templateUrl: 'views/producer.html',
  controller: 'ProducerCtrl'
})

(2) 在producers.html中,定義點擊事件,比如ng-click="toProducer(producerId)",在ProducersCtrl中,定義頁面跳轉(zhuǎn)函數(shù) (使用ui-router的$state.go接口):

.controller('ProducersCtrl', function ($scope, $state) {
  $scope.toProducer = function (producerId) {
    $state.go('producer', {producerId: producerId});
  };
});

(3) 在ProducerCtrl中,通過ui-router的$stateParams獲取參數(shù)producerId,譬如:

.controller('ProducerCtrl', function ($scope, $state, $stateParams) {
  var producerId = $stateParams.producerId;
});

2. 基于factory的頁面跳轉(zhuǎn)傳參

舉例:你有N個頁面,每個頁面都需要用戶填選信息,最終引導用戶至尾頁提交,同時后一個頁面要顯示前面所有頁面填寫的信息。這個時候用factory傳參是比較合理的選擇(下面的代碼是一個簡化版,根據(jù)需求可以不同定制):

.factory('myFactory', function () {  
  //定義參數(shù)對象
  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中通過調(diào)setter()和getter()方法可實現(xiàn)提交或獲取參數(shù)的功能
  return {
    setter: _setter,
    getter: _getter
  };
});

3. 基于factory和$rootScope.$broadcast()的傳參

(1) 舉例:在一個單頁中定義了nested views,你希望讓所有子作用域都監(jiān)聽到某個參數(shù)的變化,并且作出相應動作。比如一個地圖應用,某個$state中定義元素input,輸入地址后,地圖要定位,同時另一個狀態(tài)下的列表要顯示出該位置周邊商鋪的信息,此時多個$scope都在監(jiān)聽地址變化。

PS: $rootScope.$broadcast()可以非常方便的設置全局事件,并讓所有子作用域都監(jiān)聽到。

.factory('addressFactory', ['$rootScope', function ($rootScope) {
  // 定義所要返回的地址對象  
  var address = {};
  
  // 定義components數(shù)組,數(shù)組包括街道,城市,國家等
  address.components = [];

  // 定義更新地址函數(shù),通過$rootScope.$broadcast()設置全局事件'AddressUpdated'
  // 所有子作用域都能監(jiān)聽到該事件
  address.updateAddress = function (value) {
 this.components = angular.copy(value);
 $rootScope.$broadcast('AddressUpdated');
  };
  
  // 返回地址對象
  return address;
}]);

(2) 在獲取地址的controller中:

// 動態(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對象推入$scope.components數(shù)組
  components.push(component);
  // 更新addressFactory中的components
  addressFactory.updateAddress(components);
});

(3) 在監(jiān)聽地址變化的controller中:

// 通過addressFactory中定義的全局事件'AddressUpdated'監(jiān)聽地址變化
$scope.$on('AddressUpdated', function () {
  // 監(jiān)聽地址變化并獲取相應數(shù)據(jù)
  var street = address.components[0].addressLongName;
  var city = address.components[0].cityLongName;

  // 通過獲取的地址數(shù)據(jù)可以做相關操作,譬如獲取該地址周邊的商鋪,下面代碼為本人虛構(gòu)
  shopFactory.getShops(street, city).then(function (data) {
    if(data.status === 200){
     $scope.shops = data.shops; 
    }else{
     $log.error('對不起,獲取該位置周邊商鋪數(shù)據(jù)出錯: ', data);
    }
  });
});

4. 基于localStorage或sessionStorage的頁面跳轉(zhuǎn)傳參

注意事項:通過LS或SS傳參,一定要監(jiān)聽變量,否則參數(shù)改變時,獲取變量的一端不會更新。AngularJS有一些現(xiàn)成的WebStorage dependency可以使用,譬如gsklee/ngStorage · GitHub,grevory/https://github.com/grevory/angular-local-storage。下面使用ngStorage來簡述傳參過程:

(1) 上傳參數(shù)到localStorage - Controller A

// 定義并初始化localStorage中的counter屬性
$scope.$storage = $localStorage.$default({
  counter: 0
});

// 假設某個factory(此例暫且命名為counterFactory)中的updateCounter()方法
// 可以用于更新參數(shù)counter
counterFactory.updateCounter().then(function (data) {
  // 將新的counter值上傳到localStorage中
  $scope.$storage.counter = data.counter;
});

(2) 監(jiān)聽localStorage中的參數(shù)變化 - Controller B

$scope.counter = $localStorage.counter;
$scope.$watch('counter', function(newVal, oldVal) {
  // 監(jiān)聽變化,并獲取參數(shù)的最新值
  $log.log('newVal: ', newVal);  
});

5. 基于localStorage/sessionStorage和Factory的頁面?zhèn)鲄?/strong>

由于傳參出現(xiàn)的不同的需求,將不同方式組合起來可幫助你構(gòu)建低耦合便于擴展和維護的代碼。

舉例:應用的Authentication(授權(quán))。用戶登錄后,后端傳回一個時限性的token,該用戶下次訪問應用,通過檢測token和相關參數(shù),可獲取用戶權(quán)限,因而無須再次登錄即可進入相應頁面(Automatically Login)。其次所有的APIs都需要在HTTP header里注入token才能與服務器傳輸數(shù)據(jù)。此時我們看到token扮演一個重要角色:(a)用于檢測用戶權(quán)限,(b)保證前后端數(shù)據(jù)傳輸安全性。以下實例中使用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相關的業(yè)務邏輯,比如login,logout,checkAuthentication,getAuthenticationParams等。此處略去其他業(yè)務,只專注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;

   ////////////////

   /**
    * 定義處理錯誤函數(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ù)。
    * 若登錄成功,把服務器返回的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ù)。
    * 用于設置isAuth參數(shù)。
    * @param {type} xxx
    * @returns {*}
    * @private
    */
   function setAuthenticationParams(param) {
    $localStorage.isAuth = param;
   }
   
   /**
    * 定義獲取數(shù)據(jù)的getter函數(shù),公有函數(shù)。
    * 用于獲取isAuth和token參數(shù)。
    * 通過setter和getter函數(shù),可以避免使用第四種方法所提到的$watch變量。
    * @param {type} xxx
    * @returns {*}
    * @public
    */   
   function getAuthenticationParams() {
    var authParams = {
     isAuth: $localStorage.isAuth,
     authtoken: $localStorage.authtoken
    };
    return authParams;
   }  
   
   /* 
    * 第一步: 檢測token是否有效.
    * 若token有效,進入第二步。
    *
    * 第二步: 檢測用戶是否依舊屬于admin權(quán)限.
    *
    * 只有滿足上述兩個條件,函數(shù)才會返回true,否則返回false。 
    * 請參看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的文件,用于在應用載入時自動運行權(quán)限檢測代碼。

(function() {
 'use strict';

 angular
  .module('myApp')
  .run(checkPermission);

 /** @ngInject */
 
 /**
  * angular-permission version 3.0.x.
  * https://github.com/Narzerus/angular-permission/wiki/Managing-permissions.
  * 
  * 第一步: 運行authService.getAuthenticationParams()函數(shù).
  * 返回true:用戶之前成功登陸過。因而localStorage中已儲存isAuth和authtoken兩個參數(shù)。 
  * 返回false:用戶或許已logout,或是首次訪問應用。因而強制用戶至登錄頁輸入用戶名密碼登錄。
  *
  * 第二步: 運行authService.checkAuthentication()函數(shù).
  * 返回true:用戶的token依舊有效,同時用戶依然擁有admin權(quán)限。因而無需手動登錄,頁面將自動重定向到admin頁面。
  * 返回false:要么用戶token已經(jīng)過期,或用戶不再屬于admin權(quán)限。因而強制用戶至登錄頁輸入用戶名密碼登錄。
  */
 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的文件,用于在所有該應用請求的HTTP requests的header中注入token。關于AngularJS的Interceptor,請參看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);

以上是“angularjs項目中實現(xiàn)頁面跳轉(zhuǎn)的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI