AngularJS UI-Router 傳遞參數方法

  • 433
  • 0

AngularJS UI-Router Parameter

共有3種方法:

1.Query Parameters

state('new-qs', {
  url: '/new?portfolioId',
  templateUrl: 'new.html',
  controller: function($scope, $stateParams) {
     $scope.portfolioId = $stateParams.portfolioId;
  }
})
<a ui-sref="new-qs({ portfolioId: 1 })">New (query string)</a>

網址呈現:

/new?portfolioId=1

 

2.Optional Route Parameters

state('new-rp', {
  url: '/new/:portfolioId',
  templateUrl: 'new.html',
  controller: function($scope, $stateParams) {
     $scope.portfolioId = $stateParams.portfolioId;
  }
})

Updating the ui-sref attribute to new-rp({ portfolioId: 2 }) will produce the link /new/2.

For multiple optional route parameters e.g. /posts/tagged/:tag/page/:page it looks like the only solution right now is to declare multiple routes i.e. /posts/tagged/:tag and /posts/tagged/:tag/page/:page.

3.Non-URL route parameters

state('new-nonurl', {
  url: '/new',
  params: {
    portfolioId: null,
  },
  templateUrl: 'new.html',
  controller: function($scope, $stateParams) {
     $scope.portfolioId = $stateParams.portfolioId;
  }
})

You can also use the params object to declare default values for your route parameters.

Now ui-sref="new-nonurl({ portfolioId: 3 })" will generate the link \new but still pass the portfolioId parameter in $stateParams.

最後作者還附上了 sample code ,真不錯 

sample code: http://plnkr.co/edit/iK9y4th6XLSk0s5jvx6C?p=preview

 

參考文章: http://benfoster.io/blog/ui-router-optional-parameters