AngularJS中如何从动态路由跳转至/:userId/details/路由?
Let's get this navigation working correctly step by step. I’ve looked over your code and found a couple of key issues that are blocking the click navigation, even though direct URL access works as expected.
1. Fix the ui-sref Syntax in Your Template
Your current ui-sref has invalid syntax and points to the wrong state—this is the main issue stopping the link from working. Here’s what’s off:
- You’re trying to append a path (
/albums) directly to the state reference, which isn’t howui-srefworks. - The state name should be
detailsList(notusers) since that’s the state you defined for the details route. - You’re referencing
user.idinstead of$ctrl.user.id(your component uses controller-as syntax, so the user data lives on$ctrl). - The redundant
href='#'can be removed—ui-srefautomatically generates the correct URL.
Corrected user/user.html:
<h3>An user!</h3> <div> <div>Name: <a ui-sref="detailsList({ userId: $ctrl.user.id })"> {{$ctrl.user.name}} </a></div> <div>Id: {{$ctrl.user.id}}</div> </div>
2. Align Route URL Formats (Optional but Recommended)
Your user state URL ends with a trailing slash (/{userId}/), but the detailsList state URL doesn’t (/{userId}/details). To avoid routing inconsistencies, update the detailsList state URL to match the trailing slash pattern:
Corrected details-list/details-list.js:
.config(($stateProvider) => { "ngInject"; $stateProvider .state('detailsList', { url: '/{userId}/details/', // Added trailing slash for consistency component: 'detailsList', resolve: { albums: function(DetailsListService, $stateParams) { return DetailsListService.getAlbums($stateParams.userId); } } }); }) export default detailsListModule;
3. Quick Controller Sanity Check
Your DetailsListController looks solid—you’re correctly injecting $stateParams and capturing the userId. Just double-check that your detailsList component definition properly references this controller (it likely does, since direct URL access works).
After applying these changes, clicking the user name link will correctly navigate to the /[userId]/details/ route, matching the behavior you see when manually entering the URL in the browser.
内容的提问来源于stack exchange,提问作者user11506753

