简体   繁体   English

如何使用AngularJS ui路由器构建与URL相同的URL <ui-sref> 在控制器而不是HTML中?

[英]How to use AngularJS ui-router to build same URL as <ui-sref> in controller instead of HTML?

I'm using AngularJS's ui-router in my webapp. 我在我的web应用程序中使用AngularJS的ui-router。 I have a state that looks like this: 我有一个看起来像这样的状态:

  $stateProvider.state('mystate',
    {
      url: '/mystate/{id:int}/:slug',
      params: {
        slug: {value: null, squash: true}
      },
      templateUrl: 'partials/mystate.html',
      controller: 'MyStateCtrl'
    }
  );

I can link to this state in my view like this: 我可以这样链接到此状态:

<a ui-sref="mystate({id: 4, slug: 'myslug'})">Hello World</a>

It converts it to the following URL: /mystate/4/myslug/ 它将其转换为以下URL: /mystate/4/myslug/

I want to build the same URL that ui-sref produces, but I want it inside MyStateCtrl . 我想构建ui-sref生成的相同URL,但是我想在MyStateCtrl它。 How do I do that? 我怎么做? In the controller, I have access to $stateParams.id and $stateParams.slug . 在控制器中,我可以访问$stateParams.id$stateParams.slug But what function do I need to call to convert them to that URL? 但是我需要调用什么函数才能将它们转换为该URL?

EDIT : Please note: I do not want to go to the resultant URL. 编辑 :请注意:我不想转到结果URL。 I just want to have it for later use. 我只想拥有它供以后使用。

You can inject $state as a dependency to MyStateCtrl and use $state.go(to [, toParams] [, options]) function for navigating to target URL. 您可以将$ state注入MyStateCtrl的依赖项,并使用$state.go(to [, toParams] [, options])函数导航到目标URL。

For example: 例如:

class MainController {

  constructor($scope, $state) {
    'ngInject';

    this.scope = $scope;
    this.state = $state;

   }

   navigateToAState() {
     this.state.go('mystate',{id: 4, slug: 'myslug'})
   }
 }

 export default MainController;

Detail Reference: $state.go(to \\[, toParams\\] \\[, options\\]) 详细信息参考: $state.go(to \\[, toParams\\] \\[, options\\])

A url generation method that returns the compiled url for the given state populated with the given params. 一种url生成方法,该方法返回填充有给定参数的给定状态的已编译url。

Example : expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");

you can use this 你可以用这个

$state.href ('mystate',{id: 4, slug: 'myslug'});

See This link for more help 请参阅此链接以获取更多帮助

You can construct a url just like you ui-sref with the function $state.href() . 您可以像ui-sref一样使用$state.href()函数构造一个url。 You just need to provide the route and its params that you can get from $stateParams . 您只需要提供可以从$stateParams获得的路线及其参数。

e.g. expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");

So in your case: 因此,在您的情况下:

$state.href("mystate", { id: $stateParams.id, slug: $stateParams.slug });

And here is the documentation - $state.href() 这是文档- $ state.href()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM