I have a rather complicated prototype app that I have been asked to throw together... now in my app I have some routes / states defined using UI-Router, here is some code from my app.js file, you can see one parent and child route / state:
.state('myapp.loggedInHome.contacts.default', {
url: '/:profileId', // this could be myurl.com/home/contacts/31333194
template: '<ui-view/>',
publicAccess: false
})
// nested state for contacts profile...
.state('myapp.loggedInHome.contacts.default.news', {
url: '/news', // this could be myurl.com/home/contacts/31333194/news
templateUrl: '/prototype/app/people/views/news.html',
publicAccess: false,
controller: 'VisitorsNewsCtrl'
})
Now in the VisitorsNewsCtr
l controller I want to access the :profileId
as defined in the parent root... however when I try to access this using the $stateParams
service I get undefined
! What am I doing wrong in my controller?
.controller('VisitorsCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
console.log($stateParams.profileId); // this is undefined as
// $stateParams is an empty object
I am redirecting to this state like so...
$state.go('myapp.loggedInHome.contacts.default.news', { profileId: 123456 } );
however the value for profileId
is undefined? But the value appears in the URL!
You need to add the potential params to the url in your state definition like this: url: '/news/:profileId'
If you use $state.go('myapp.loggedInHome.contacts.default.news', {profileId: 1234})
you should then be able to access $stateParams.profileId
Example definition:
$stateProvider
.state('contacts.detail', {
url: "/contacts/:contactId",
templateUrl: 'contacts.detail.html',
controller: function ($stateParams) {
// If we got here from a url of /contacts/42
expect($stateParams).toBe({contactId: "42"});
}
})
I managed to get the value by using the $state
object!
Like so...
.controller('VisitorsCtrl', ['$scope', '$state', function ($scope, $state) {
console.log($state.params.profileId);
Honestly (despite two other answers) the problem is, that this defintion:
.controller('VisitorsCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
console.log($stateParams.profileId);
...
Is about controller 'VisitorsCtrl'
. While the state says 'VisitorsNewsCtrl'
:
.state('myapp.loggedInHome.contacts.default.news', {
url: '/news', // this could be myurl.com/home/contacts/31333194/news
templateUrl: '/prototype/app/people/views/news.html',
publicAccess: false,
controller: 'VisitorsNewsCtrl'
})
So, if the controller will match I am sure that the syntax with $stateParams will work
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.