I'm using AngularJS's ui-router in my webapp. 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/
I want to build the same URL that ui-sref
produces, but I want it inside MyStateCtrl
. How do I do that? In the controller, I have access to $stateParams.id
and $stateParams.slug
. But what function do I need to call to convert them to that URL?
EDIT : Please note: I do not want to go to the resultant 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.
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\\])
A url generation method that returns the compiled url for the given state populated with the given params.
Example : expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
you can use this
$state.href ('mystate',{id: 4, slug: 'myslug'});
You can construct a url just like you ui-sref with the function $state.href()
. You just need to provide the route and its params that you can get from $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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.