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

posted on 2016-09-02 00:47  ilinux_one  阅读(5496)  评论(0编辑  收藏  举报

导航