大家好,我是IT修真院鄭州分院第三期的學員王相博,一枚正直、純潔、善良的前端程序員
今天給大家分享一下,修真院官網JS(職業)任務7,深度思考中的知識點——如何使用ui-router進行傳參?
1.背景介紹
今天的內容是在angular中使用ui-router時在不同頁面之間跳轉并傳遞參數
2.知識剖析
首先在angular之中實現路由跳轉功能有其自帶的ngRoute還有常用的第三方插件ui-router
選擇ui-router來替代自帶的ngRouter是因為它更好用更靈活,具體對比則不是本次分享內容
想要頁面之間傳遞參數,則首先要實現跳轉
使用ui-router實現跳轉有兩種方式
一種是使用其ui-sref指令,另一種是使用$state.go()方法
$state.go()方法
通常用在controller里面,如
.controller('heiheihei', function($scope, $state) { ? ? ? ? ? ? ? ? ? ?$state.go('login'); ? ? ? ? ? ? ? ? ? ?});
ui-sref方法
通常用在a標簽里面或者按鈕跳轉之類
查看ui-sref的源碼可得這兩種方法本質上是一樣的
element.bind("click", function(e) { ? ? ? ? ? ? ? ?var button = e.which || e.button; ? ? ? ? ? ? ? ?if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) { ? ? ? ? ? ? ? ?var transition = $timeout(function() { ? ? ? ? ? ? ? ?// HERE we call $state.go inside of ui-sref ? ? ? ? ? ? ? ?$state.go(ref.state, params, options); ? ? ? ? ? ? ? ?});
ui-sref最后也是調用了$state.go()方法
具體如何實現傳參呢
首先,要在目標頁面定義接受的參數:ui-sref傳參$state.go傳參3.常見問題
獲取傳遞的參數
4.解決方案
在目標頁面的controller里注入$stateParams,然后 "$stateParams.參數名" 獲取5.編碼實戰
6.擴展思考
url傳參時如何處理
url傳參時同樣需要在url中事先配置,如
.state("field.positionDetails", { ? ? ? ? ? ?url: "/positionDetails?companyId?companyName?id", ? ? ? ? ? ?templateUrl: "html/list/positionDetails.html", ? ? ? ?})
在url后接?以及傳遞的內容
7.參考文獻
8.更多討論
還有其他傳參的方法嗎?