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¶m1¶m2',
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>
Can someone explain how I can route to a Url using parameters?
E.g. id like to click on a product and open more info of the product by Id.
My Routing so far ...
angular.module('shop', ["customFilters", "cart", "ngRoute"])
.config(function ($routeProvider){
$routeProvider.when("/complete", {
templateUrl: "../app/views/orderComplete.html"
});
$routeProvider.when("/placeorder", {
templateUrl: "../app/views/placeOrder.html"
});
$routeProvider.when("/checkout", {
templateUrl: "../app/views/checkoutSummary.html"
});
$routeProvider.when("/products", {
templateUrl: "../app/views/productList.html"
});
$routeProvider.when("/product:", {
templateUrl: "../app/views/product.html"
});
$routeProvider.otherwise({
templateUrl: "../app/views/productList.html"
});
});
So By clicking ...
<a class="btn btn-default" href="#/product/{{item.id}}">More Info</a>
Id like to be routed to product/{{id}}.html ...
Can someone advise what I am missing in ...
$routeProvider.when("/product:id", {
templateUrl: "../app/views/product.html"
});
2 things, but you are basically there.
First you are missing a slash before the URL param. Happens to the best of us.
routeProvider.when("/product/:id", {
templateUrl: "../app/views/product.html"
});
Secondly you should use ng-href instead href when you have dynamic URL params.
<a ng-href="#/product/{{item.id}}">More Info</a>
I thinks this issue is duplicate, see response How to pass parameters using ui-sref in ui-router to controller
you can send paramters to state name as home({foo: 'fooVal1', bar: 'barVal1'})
with a url '/:foo?bar'
see this exemple:
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
and send values as:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
Question: For some reason I can't get my controller to recognize my url parameters across sessions.
Background: I have a nested view called modal that takes a parameter, whose url is /modal/:id (eg: /#/modal/1/ or /#/floorplan/1+2/). Ideally, when the user goes to this url, a modal will automatically open with the resource(s) with the given id.
Since the parent state and the child state(modal) are being handled by the same controller, the modal state has a custom data attribute (modalStatus) in its configuration set to true. When this custom attribute is enabled the modal is displayed.
I can currently go from the parent state to the nested state and trigger the modal but when I start a new session or refresh the page with a url like /modal/3, the application fails to read the parameters ($stateParams), which is being logged as an empty object.
I have tried using onEnter and Resolve but I'm not exactly clear on how to use them in this scenario.
Router
$stateProvider
.state('home', {
name: 'home',
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.state('home.modal', {
url: 'modal/:id/',
data: {
modalState: true
},
controller: 'MainCtrl'
})
Relevant part of controller:
$scope.init = function() {
console.log($stateParams);
if ($state.current.data) {
if ($state.current.data.modalState === true) {
$scope.openModal();
}
}
};
$scope.init();
edit: plunkr
You could try adding the params option:
$stateProvider
.state('home', {
name: 'home',
params: {
id: null
},
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.state('home.modal', {
url: 'modal/:id/',
data: {
modalState: true
},
controller: 'MainCtrl'
});
The child state home.modal should inherit the params of the parent. On your ui-sref from one state to another, pass the param like so:
<a ui-sref="home.modal({ id: x })"></a>
Then your url would turn out to be /modal/:x (where x is the number).
Also the $stateParams should then show the params as you wished.
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);
}]
});
I am using AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I want to pass the referrer state to another state so I use the toParams of $state.go like so:
$state.go('toState', {referer: $state.current.name});
According to the docs, this should populate the $stateParams on the toState controller, but it is undefined. What am I missing?
I've created a plunk to demonstrate:
http://plnkr.co/edit/ywEcG1
If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.
$stateProvider.state('toState', {
templateUrl:'wokka.html',
controller:'stateController',
params: {
'referer': 'some default',
'param2': 'some default',
'etc': 'some default'
}
});
Then you can navigate to it like so:
$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });
Or:
var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);
And in HTML thusly:
<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>
This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.
The Nathan Matthews's solution did not work for me but it is totally correct but there is little point to reaching a workaround:
The key point is: Type of defined parameters and toParamas of $state.go should be same array or object on both sides of state transition.
For example when you define a params in a state as follows you means params is array because of using "[]":
$stateProvider
.state('home', {
templateUrl: 'home',
controller: 'homeController'
})
.state('view', {
templateUrl: 'overview',
params: ['index', 'anotherKey'],
controller: 'overviewController'
})
So also you should pass toParams as array like this:
params = { 'index': 123, 'anotherKey': 'This is a test' }
paramsArr = (val for key, val of params)
$state.go('view', paramsArr)
And you can access them via $stateParams as array like this:
app.controller('overviewController', function($scope, $stateParams) {
var index = $stateParams[0];
var anotherKey = $stateParams[1];
});
Better solution is using object instead of array in both sides:
$stateProvider
.state('home', {
templateUrl: 'home',
controller: 'homeController'
})
.state('view', {
templateUrl: 'overview',
params: {'index': null, 'anotherKey': null},
controller: 'overviewController'
})
I replaced [] with {} in params definition. For passing toParams to $state.go also you should using object instead of array:
$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })
then you can access them via $stateParams easily:
app.controller('overviewController', function($scope, $stateParams) {
var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
});
All I had to do was add a parameter to the url state definition like so
url: '/toState?referer'
Doh!
Not sure if it will work with AngularJS v1.2.0-rc.2 with ui-router v0.2.0.
I have tested this solution on AngularJS v1.3.14 with ui-router v0.2.13.
I just realize that is not necessary to pass the parameter in the URL as gwhn recommends.
Just add your parameters with a default value on your state definition.
Your state can still have an Url value.
$stateProvider.state('state1', {
url : '/url',
templateUrl : "new.html",
controller : 'TestController',
params: {new_param: null}
});
and add the param to $state.go()
$state.go('state1',{new_param: "Going places!"});
None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.
In the state add your params to end of state and define the params:
url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}
In your controller your go statement will look like this:
$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });
Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):
var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!
In my case I tried with all the options given here, but no one was working properly (angular 1.3.13, ionic 1.0.0, angular-ui-router 0.2.13). The solution was:
.state('tab.friends', {
url: '/friends/:param1/:param2',
views: {
'tab-friends': {
templateUrl: 'templates/tab-friends.html',
controller: 'FriendsCtrl'
}
}
})
and in the state.go:
$state.go('tab.friends', {param1 : val1, param2 : val2});
Cheers
I've spent a good deal of time fighting with Ionic / Angular's $state & $stateParams;
To utilize $state.go() and $stateParams you must have certain things setup and other parameters must not be present.
In my app.config() I've included $stateProvider and defined within it several states:
$stateProvider
.state('home', {
templateUrl: 'home',
controller: 'homeController'
})
.state('view', {
templateUrl: 'overview',
params: ['index', 'anotherKey'],
controller: 'overviewController'
})
The params key is especially important. As well, notice there are NO url keys present... utilizing stateParams and URLs do NOT mix. They are mutually exclusive to each other.
In the $state.go() call, define it as such:
$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })
The index and anotherKey $stateParams variables will ONLY be populated if they are first listed in the $stateController params defining key.
Within the controller, include $stateParams as illustrated:
app.controller('overviewController', function($scope, $stateParams) {
var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
});
The passed variables should be available!
Try With reload: true?
Couldn't figure out what was going on for the longest time -- turns out I was fooling myself. If you're certain that things are written correctly and you will to use the same state, try reload: true:
.state('status.item', {
url: '/:id',
views: {...}
}
$state.go('status.item', { id: $scope.id }, { reload: true });
Hope this saves you time!
I'd faced a similar problem. I ended up with a working solution after a lot of googling and trial and test. Here is my solution which would work for you.
I have two controllers - searchBoxController and stateResultController and a parameter named searchQuery to be passed from a view having a search box to a view showing the results fetched from a remote server. This is how you do it:
Below is the controller from which you call the next view using $state.go()
.controller('searchBoxController', function ($scope, $state) {
$scope.doSearch = function(){
var searchInputRaw = $scope.searchQueryInput;
$state.go('app.searchResults', { searchQuery: searchInput });
}
})
Below is the state that would be called when the $state.go() gets executed:
.state('app.searchResults',
{
url: '/searchResults',
views:
{
'menuContent': { templateUrl: 'templates/searchResult.html', controller: 'stateResultController' }
},
params:
{
'searchQuery': ''
}
})
And finally, the controller associated with the app.searchResults state:
.controller('stateResultController', function ($scope, $state, $stateParams, $http) {
$scope.searchQueryInput = $stateParams.searchQuery;
});
And in my case of a parent/child state. all the parameters declared in child state has to be known by the parent state
.state('full', {
url: '/full',
templateUrl: 'js/content/templates/FullReadView.html',
params: { opmlFeed:null, source:null },
controller: 'FullReadCtrl'
})
.state('full.readFeed', {
url: '/readFeed',
views: {
'full': {
templateUrl: 'js/content/templates/ReadFeedView.html',
params: { opmlFeed:null, source:null },
controller: 'ReadFeedCtrl'
}
}
})
The solution we came to having a state that took 2 parameters was changing:
.state('somestate', {
url: '/somestate',
views: {...}
}
to
.state('somestate', {
url: '/somestate?id=:&sub=:',
views: {...}
}
Your define following in router.js
$stateProvider.state('users', {
url: '/users',
controller: 'UsersCtrl',
params: {
obj: null
}
})
Your controller need add $stateParams.
function UserCtrl($stateParams) {
console.log($stateParams);
}
You can send an object by parameter as follows.
$state.go('users', {obj:yourObj});
I was trying to Navigate from Page 1 to 2, and I had to pass some data as well.
In my router.js, I added params name and age :
.state('page2', {
url: '/vehicle/:source',
params: {name: null, age: null},
.................
In Page1, onClick of next button :
$state.go("page2", {name: 'Ron', age: '20'});
In Page2, I could access those params :
$stateParams.name
$stateParams.age
If this is a query parameter that you want to pass like this:
/toState?referer=current_user
then you need to describe your state like this:
$stateProvider.state('toState', {
url:'toState?referer',
views:{'...'}
});
source: https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters