欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

AngularJS頁(yè)面?zhèn)鲄⒌?種方式

 更新時(shí)間:2017年04月01日 14:30:34   作者:培培3514  
Angular頁(yè)面?zhèn)鲄⒂卸喾N辦法,根據(jù)不同用例,本文介紹5種最常見的頁(yè)面?zhèn)鲄⒌姆绞?。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧

Angular頁(yè)面?zhèn)鲄⒂卸喾N辦法,根據(jù)不同用例,我舉5種最常見的(請(qǐng)?jiān)诰W(wǎng)頁(yè)版知乎瀏覽答案):

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è)面填寫的信息。這個(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)聽到某個(gè)參數(shù)的變化,并且作出相應(yīng)動(dòng)作。比如一個(gè)地圖應(yīng)用,某個(gè)state中定義元素input,輸入地址后,地圖要定位,同時(shí)另一個(gè)狀態(tài)下的列表要顯示出該位置周邊商鋪的信息,此時(shí)多個(gè)scope都在監(jiān)聽地址變化。

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

.factory('addressFactory', ['$rootScope', function ($rootScope) {
  // 定義所要返回的地址對(duì)象  
  var address = {};
  // 定義components數(shù)組,數(shù)組包括街道,城市,國(guó)家等
  address.components = [];
  // 定義更新地址函數(shù),通過(guò)$rootScope.$broadcast()設(shè)置全局事件'AddressUpdated'
  // 所有子作用域都能監(jiān)聽到該事件
  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)聽地址變化的controller中:

// 通過(guò)addressFactory中定義的全局事件'AddressUpdated'監(jiān)聽地址變化
$scope.$on('AddressUpdated', function () {
  // 監(jiān)聽地址變化并獲取相應(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)聽變量,否則參數(shù)改變時(shí),獲取變量的一端不會(huì)更新。AngularJS有一些現(xiàn)成的WebStorage dependency可以使用,譬如gsklee/ngStorage · GitHub,grevory/angular-local-storage · GitHub。下面使用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)聽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的頁(yè)面?zhèn)鲄?

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

舉例:應(yīng)用的Authentication(授權(quán))。用戶登錄后,后端傳回一個(gè)時(shí)限性的token,該用戶下次訪問應(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,或是首次訪問應(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); 
   }
  }
})();

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

  • 小談angular ng deploy的實(shí)現(xiàn)

    小談angular ng deploy的實(shí)現(xiàn)

    這篇文章主要介紹了小談angular ng deploy的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • 利用Angular.js編寫公共提示模塊的方法教程

    利用Angular.js編寫公共提示模塊的方法教程

    最近工作中會(huì)經(jīng)常遇到一些公用提示,使用框架自帶很多時(shí)候不方便所以便自己編寫了一個(gè)公共提示模塊,下面這篇文章主要介紹了利用Angular.js編寫公共提示模塊的方法教程,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-05-05
  • angular中的http攔截器Interceptors的實(shí)現(xiàn)

    angular中的http攔截器Interceptors的實(shí)現(xiàn)

    本篇文章主要介紹了angular中的http攔截器Interceptors的實(shí)現(xiàn)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-02-02
  • 詳解Angular路由 ng-route和ui-router的區(qū)別

    詳解Angular路由 ng-route和ui-router的區(qū)別

    這篇文章主要介紹了詳解Angular路由 ng-route和ui-router的區(qū)別,分別介紹了兩種路由的用法和區(qū)別,有興趣的可以了解一下
    2017-05-05
  • Angularjs使用過(guò)濾器完成排序功能

    Angularjs使用過(guò)濾器完成排序功能

    這篇文章主要為大家詳細(xì)介紹了Angularjs使用過(guò)濾器完成排序功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • Angular中sweetalert彈框的基本使用教程

    Angular中sweetalert彈框的基本使用教程

    這篇文章主要給大家介紹了關(guān)于Angular中sweetalert彈框的基本使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-07-07
  • Angularjs中使用Filters詳解

    Angularjs中使用Filters詳解

    本文給大家總結(jié)了下在Angularjs的模板、控制器、或者服務(wù)中使用Filters的方法,有需要的小伙伴可以參考下
    2016-03-03
  • angular forEach方法遍歷源碼解讀

    angular forEach方法遍歷源碼解讀

    這篇文章主要為大家詳細(xì)了angular forEach方法遍歷源碼,forEach()方法用于遍歷對(duì)象或數(shù)組,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • AngularJS使用ng-options指令實(shí)現(xiàn)下拉框

    AngularJS使用ng-options指令實(shí)現(xiàn)下拉框

    這篇文章主要介紹了AngularJS使用ng-options指令實(shí)現(xiàn)下拉框效果,ng-option指令使用也很簡(jiǎn)單,下文具體給大家說(shuō)明,對(duì)angularjs 下拉框知識(shí)感興趣的朋友一起看下吧
    2016-08-08
  • angular4 共享服務(wù)在多個(gè)組件中數(shù)據(jù)通信的示例

    angular4 共享服務(wù)在多個(gè)組件中數(shù)據(jù)通信的示例

    本篇文章主要介紹了angular4 共享服務(wù)在多個(gè)組件中數(shù)據(jù)通信的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03

最新評(píng)論