在 Angularjs 中 ui-sref 和 $state.go 如何傳遞參數


  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.參數名" 獲取

  

  補充資料:  

<a ui-sref="man({id:1,name:2})" >按鈕</a> 

  路由里面配置:

$stateProvider.state('man', {  
    url: '/man.html?id&name',         //參數必須先在這邊聲明  
    templateUrl: '../man.html',  
})  

  點擊連接后,瀏覽器的地址則會變為:/man.html/id=1&name=2,或者也可以這樣

 
$stateProvider.state('man', {  
    url: '/man.html',           
    templateUrl: '../man.html',  
    params: {'id': null,'name':null},//參數在這邊聲明  
  
})  


  然后在對應的controller里面通過$stateParams取值:$stateParams.id,$stateParams.name

 

復制代碼


免責聲明!

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



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