天天看點

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

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

ui-sref

一般使用在

<a>...</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 >  || 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 如何傳遞參數

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

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

傳參,

ui-sref:

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

$state.go:

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

接收參數,

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

在目标頁面的controller裡注入 stateParams,然後" stateParams.參數名” 擷取