$stateProvider params null with ionic - angularjs

I can't retrieve parameters passed from ui-router in Ionic.
Parameters passed into the Controller are undefined
This is my state code:
.state('app.dayliston', {
cache: false,
url: '/myurl',
views: {
'mainContent': {
templateUrl: 'calendar/daylist.html',
controller: 'MyCtrl',
params : { 'mode':'online'}
}
}
})
and here is My Controller code:
.controller('MyCtrl', function($scope,$state, $stateParams,CalendarFactory,FBFactory, $ionicHistory,$ionicScrollDelegate,$ionicModal,$ionicPopup, $timeout) {
console.log('MyCtrl')
console.log('mode'+$stateParams.mode) // mode is undefined
....
})
I'm using 1.6.1. Is there anything wrong with my code?

As I can see in your code, you dont need to use $stateParams because you don't get the "mode" parameter from the URL.
I think attached data in state will be a better choice (Docs):
.state('app.dayliston', {
cache: false,
url: '/myurl',
data:{
mode: 'online'
},
views: {
'mainContent': {
templateUrl: 'calendar/daylist.html',
controller: 'MyCtrl'
}
}
})
Then you can get the data stored in state like this:
.controller('MyCtrl', function($scope, $state, $stateParams, CalendarFactory, FBFactory, $ionicHistory, $ionicScrollDelegate, $ionicModal, $ionicPopup, $timeout) {
console.log('MyCtrl')
console.log('mode'+$state.current.data.mode) // "online"
})

MyCtrl is the actual name of your controller. It's not a parameter that's passed to the controller per se.

Route:
.state('app.dayliston', {
cache: false,
url: '/myurl/:mode',
views: {
'mainContent': {
templateUrl: 'calendar/daylist.html',
controller: 'MyCtrl'
}
}
})
Check URL Routing Query Parameters doc
Link from view:
<a ui-sref="app.dayliston({mode: 'online'});">Go to dayliston</a>
Go to state/route from controller:
$state.go('app.dayliston', {mode: 'online'});

you are passing the $stateParams incorrectly
https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service
The should be on the url or you can pass data in using the resolve map on the state.
https://github.com/angular-ui/ui-router/wiki#resolve
also passing in custom data might be a better approach? Hard to tell from the code sample you provided

Related

How to add parameter in state `url` in angularjs

I am trying to add a parameter to my angular application. actually my app will dynamically called as :
"https://abc.ss.com/xx/sn=1234568505
to handle this state - in my $stateProvider - I am trying like this:
.state('serialCreateCase', {
url: '/sn=*', //but not working
templateUrl:'abxy.html',
controller: 'controllersss as ctrl',
}
})
But my URL is not capturing redirecting to default page. how to add the = parameter?
Try this:
.state('serialCreateCase', {
url: '^/sn={id}',
params: {
id: {}
},
templateUrl:'abxy.html',
controller: 'controllersss as ctrl',
}
That should match the url you're expecting.
Edit: answer has been updated to change it to required parameters.
Did you try this: http://benfoster.io/blog/ui-router-optional-parameters
Query Parameters
So that query parameters are mapped to UI Router's $stateParams object, you need to declare them in your state configuration's URL template:
state('new-qs', {
url: '/new?portfolioId',
templateUrl: 'new.html',
controller: function($scope, $stateParams) {
$scope.portfolioId = $stateParams.portfolioId;
}
})
You can then create a link to this state using the ui-sref attribute:
<a ui-sref="new-qs({ portfolioId: 1 })">New (query string)</a>
This will navigate to /new?portfolioId=1.
If you have multiple optional parameters, separate them with an &:
state('new-qs', {
url: '/new?portfolioId&param1&param2',
templateUrl: 'new.html',
controller: function($scope, $stateParams) {
$scope.portfolioId = $stateParams.portfolioId;
$scope.param1 = $stateParams.param1;
$scope.param2 = $stateParams.param2;
}
})
You could add params like this
state('serialCreateCase', {
url: '/xx?sn',
templateUrl: 'abxy.html',
controller: 'controllersss as ctrl',
}
})
The state ref will be
<a ui-sref="serialCreateCase({ sn: 1234568505 })">URL</a>

UI Router $stateparams not registering in $state.go()

I'm trying to go very simply to another state programatically and pass parameters, so:
$stateService.go('login', {
messages: [{
service: 'Auth',
type: 'error',
msg: "Your session has expired. Please log in to continue..."
}]
});
$stateService is to avoid circular dependancy between ui-router and state (both of which use $http)
var $stateService = $injector.get('$state');
This is the login state, as loaded into $stateProvider:
angular
.module('kitchenapp')
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login/login.html',
controller: 'LoginCtrl',
controllerAs: 'vm'
});
}]);
When I go to the login controller, however
angular
.module('kitchenapp.controllers')
.controller('LoginCtrl', LoginCtrl);
LoginCtrl.$inject = ['$location', 'Auth', 'toastr', '$stateParams', '$log'];
function LoginCtrl($location, Auth, toastr, $stateParams, $log) {
var vm = this;
angular.extend(vm, {
name: 'LoginCtrl',
messages: $stateParams.messages,
...
$stateParams.messages is empty. What am I doing wrong?
Any parameter which should be part of state must be defined. Either in url or via params: {} object:
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login/login.html',
controller: 'LoginCtrl',
controllerAs: 'vm',
params: { messages : null },
});
Check more details:
How to pass parameters using ui-sref in ui-router to controller
You should register "messages" parameter within the state. See https://github.com/angular-ui/ui-router/wiki/URL-Routing#important-stateparams-gotcha

ui-router: Integrating with existing controllers

I am in the process of converting my current angular project to use ui-router and I am a little confused. The documentation states I add my controller as such:
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: function($stateParams){
$stateParams.contactId //*** Exists! ***//
}
})
I have defined my old controller in this manner:
xap.controller('DemoCtrl', [$scope, function ($scope, demoService) {
})
where xap is defined as:
var xap = angular.module({ .... })
What is the correct integration method?
Thanks
You can refer to a pre-registered controller by name:
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: 'DemoCtrl'
});
You can add the $stateParams dependency to your controller to access parameters:
xap.controller('DemoCtrl', [
'$scope',
'$stateParams',
'demoService',
function ($scope, $stateParams, demoService) {
$stateParams.contactId //*** Exists! ***//
}
]);
But you can also inline your controllers and therefore not have to come up with unique names for each controller for every state:
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: [
'$scope',
'$stateParams',
'demoService',
function ($scope, $stateParams, demoService) {
$stateParams.contactId //*** Exists! ***//
}
]
});
The controller in the state is not a resolve field.
In the state, you have to put only controller name because when you declare it, it's "injected" into your angular module.
So, you have to put controller name like this :
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: 'ContactsCtrl'
});
If you want to inject some variable, you can add an object in the state like this :
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: 'ContactsCtrl',
myVar: function(...){
return '...';
}
});
So, if you put a function, it's for a resolve field and not for controllers... You can implement it into state but it's better to do it outside state declaration.

Ionic $state.go not working on device

I'm currently working on an app, build using Ionic. My problem is that $state.go is only working in the browser but not on the phone. This seem to be a common problem, but after reading a lot of answers to the same questions, I still can't figure out how to fix it.
The general fix seems to be to ensure you're using relative URLs as explained here: Using Angular UI-Router with Phonegap but I still can't get it to work. What am I missing?
Link to plunker: http://plnkr.co/edit/qFJ1Ld6bhKvKMkSmYQC8?p=preview
App.js structure:
....
$stateProvider
.state('parent', {
url: "/",
templateUrl: "parent.html"
})
.state('parent.child', {
url: "child",
templateUrl: "child.html"
})
$urlRouterProvider.otherwise("/")
})
....
For state.go to work you have to inject $state dependency to your controller
app.controller('ParentCtrl', ['$scope', '$state', function($scope, $state) {
$scope.$state = $state
}]);
app.controller('MenuCtrl', ['$scope', '$state', function($scope, $state){
$scope.goTo = function(){
$state.go('menu.kategorier');
}
}]);
and you have to register the state you want to goto in $stateProvider
$stateProvider
.state('menu.kategorier', {...})
and to get to that state you have to go from parent state like 'menu' in this case. you cannot change state from 'parent' to 'menu.kategorier' but you can goto 'parent.child' from 'parent'
I solved it by changing my setup for the nested views, based on this example: http://codepen.io/mhartington/pen/Bicmo
Here is my plunker, for those who are interested:
Plunker: http://plnkr.co/edit/2m5bljMntpq4P2ccLrPD?p=preview
app.js structure:
$stateProvider
.state('eventmenu', {
url: "/event",
abstract: true,
template: "<ion-nav-view name='menuContent'></ion-nav-view>"
})
.state('eventmenu.home', {
url: "/home",
views: {
'menuContent' :{
templateUrl: "home.html"
}
}
})
.state('eventmenu.home.home1', {
url: "/home1",
views: {
'inception' :{
templateUrl: "home1.html"
}
}
})

Angular ui-router to accomplish a conditional view

I am asking a similar question to this question: UI Router conditional ui views?, but my situation is a little more complex and I cannot seem to get the provided answer to work.
Basically, I have a url that can be rendered two very different ways, depending on the type of entity that the url points to.
Here is what I am currently trying
$stateProvider
.state('home', {
url : '/{id}',
resolve: {
entity: function($stateParams, RestService) {
return RestService.getEntity($stateParams.id);
}
},
template: 'Home Template <ui-view></ui-view>',
onEnter: function($state, entity) {
if (entity.Type == 'first') {
$state.transitionTo('home.first');
} else {
$state.transitionTo('home.second');
}
}
})
.state('home.first', {
url: '',
templateUrl: 'first.html',
controller: 'FirstController'
})
.state('home.second', {
url: '',
templateUrl: 'second.html',
controller: 'SecondController'
});
I set up a Resolve to fetch the actual entity from a restful service.
Every thing seems to be working until I actually get to the transitionTo based on the type.
The transition seems to work, except the resolve re-fires and the getEntity fails because the id is null.
I've tried to send the id to the transitionTo calls, but then it still tries to do a second resolve, meaning the entity is fetched from the rest service twice.
What seems to be happening is that in the onEnter handler, the state hasn't actually changed yet, so when the transition happens, it thinks it is transitioning to a whole new state rather than to a child state. This is further evidenced because when I remove the entity. from the state name in the transitionTo, it believes the current state is root, rather than home. This also prevents me from using 'go' instead of transitionTo.
Any ideas?
The templateUrl can be a function as well so you check the type and return a different view and define the controller in the view rather than as part of the state configuration. You cannot inject parameters to templateUrl so you might have to use templateProvider.
$stateProvider.state('home', {
templateProvider: ['$stateParams', 'restService' , function ($stateParams, restService) {
restService.getEntity($stateParams.id).then(function(entity) {
if (entity.Type == 'first') {
return '<div ng-include="first.html"></div>;
} else {
return '<div ng-include="second.html"></div>';
}
});
}]
})
You can also do the following :
$stateProvider
.state('home', {
url : '/{id}',
resolve: {
entity: function($stateParams, RestService) {
return RestService.getEntity($stateParams.id);
}
},
template: 'Home Template <ui-view></ui-view>',
onEnter: function($state, entity) {
if (entity.Type == 'first') {
$timeout(function() {
$state.go('home.first');
}, 0);
} else {
$timeout(function() {
$state.go('home.second');
}, 0);
}
}
})
.state('home.first', {
url: '',
templateUrl: 'first.html',
controller: 'FirstController'
})
.state('home.second', {
url: '',
templateUrl: 'second.html',
controller: 'SecondController'
});
I ended up making the home controller a sibling of first and second, rather than a parent, and then had the controller of home do a $state.go to first or second depending on the results of the resolve.
Use verified code for conditional view in ui-route
$stateProvider.state('dashboard.home', {
url: '/dashboard',
controller: 'MainCtrl',
// templateUrl: $rootScope.active_admin_template,
templateProvider: ['$stateParams', '$templateRequest','$rootScope', function ($stateParams, templateRequest,$rootScope) {
var templateUrl ='';
if ($rootScope.current_user.role == 'MANAGER'){
templateUrl ='views/manager_portal/dashboard.html';
}else{
templateUrl ='views/dashboard/home.html';
}
return templateRequest(templateUrl);
}]
});

Resources