ui-router參數傳遞


基本參數:

‘/user/:id'

'/user/{id}'

'/user/{id:int}'

 

使用正則表達式:

'/user/{id:[0-9]{1,8}'

 

'/user/{id:.*}'

'/user/*id 

匹配所有以user開始的url 並將剩余參數傳給id

 

多個參數:

‘/user?id1&id2'

 

$StateParams service

 

// If you had a url on your state of:
url: '/users/:id/details/{type}/{repeat:[0-9]+}?from&to'

// Then you navigated your browser to:
'/users/123/details//0'

// Your $stateParams object would be
{ id:'123', type:'', repeat:'0' }

// Then you navigated your browser to:
'/users/123/details/default/0?from=there&to=here'

// Your $stateParams object would be
{ id:'123', type:'default', repeat:'0', from:'there', to:'here' }

 

$StateParams僅包含注冊在當前狀態下的參數,不包含其他狀態下的參數,即使是上級的url參數也獲取不到

 

$stateProvider.state('contacts.detail', { url: '/contacts/:contactId', controller: function($stateParams){ $stateParams.contactId //*** Exists! ***// } }).state('contacts.detail.subitem', { url: '/item/:itemId', controller: function($stateParams){ $stateParams.contactId //*** Watch Out! DOESN'T EXIST!! ***// $stateParams.itemId //*** Exists! ***// } })

 若想讓下級獲取到當前狀態的參數,需使用resolve()。該函數會在畫面渲染出來前先執行完成。

 

 

$stateProvider.state('contacts.detail', { url: '/contacts/:contactId', controller: function($stateParams){ $stateParams.contactId //*** Exists! ***// }, resolve:{ contactId: ['$stateParams', function($stateParams){ return $stateParams.contactId; }] } }).state('contacts.detail.subitem', { url: '/item/:itemId', controller: function($stateParams, contactId){ contactId //*** Exists! ***// $stateParams.itemId //*** Exists! ***// } })

 

1 ui-sref、$state.go 的區別

ui-sref 一般使用在 <a>...</a>;

<a ui-sref="message-list">消息中心</a>

$state.go('someState')一般使用在 controller里面;

.controller('firstCtrl', function($scope, $state) {
      $state.go('login');
 });

這兩個本質上是一樣的東西,我們看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()方法

 

2 如何傳遞參數

 

首先,要在目標頁面定義接受的參數:

 

傳參,

ui-sref:

$state.go:

 

接收參數,

在目標頁面的controller里注入$stateParams,然后 "$stateParams.參數名" 獲取

 
分類:  javascript


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM