AngularJS Route : set several parameters values for the same route - angularjs

I was wondering if it was possible with AngularJS to do something like this :
I currently have a route with a first parameter called 'resource' that can be "device" or "group". There is a second parameter called 'id' but it doesn't matter. With the following code the route accepts anything as first parameter :
.when("/templates/:resource/:id", {
templateUrl: "/templates/views/navigation/templates.html",
controller: 'ctrlTemplates',
tab: "templates",
})
It makes me check in the controller if the value of the first parameter is either 'device' or 'group'. I would like to get rid of this verification part without creating two routes if possible :
.when("/templates/group/:id", {
templateUrl: "/templates/views/navigation/templates.html",
controller: 'ctrlTemplates',
tab: "templates",
})
.when("/templates/device/:id", {
templateUrl: "/templates/views/navigation/templates.html",
controller: 'ctrlTemplates',
tab: "templates",
})
So my question is, is it possible, using ONE route, to have several urls ? Something like this for instance :
.when("/templates/('device'|'group')/:id", {
templateUrl: "/templates/views/navigation/templates.html",
controller: 'ctrlTemplates',
tab: "templates",
})
So I don't have to check the value of the parameter afterwards in the controller myself using
if([('group', 'device'].includes($routeParams.resource))...
Do you know if it's possible ? Or a similar way to do it?
Best regards,

You can't do what you want. If you want to use ui-router you can pull it off but AngularJS ngRoute does not give you the ability to use regexes, or bind route parameters to types. If you are willing to switch to ui-router I can give you an example of how to do what you want.

I am willing to switch to ui-router if it can help me achieve what I want to do.
Also, if it supports types it's nice as I have parameters that must be integers. I am going to have a look at some examples.
If you have any example with regexes It would be nice !

Related

Dynamic nested routing in angularJs

Trying to implement the following route system with angular stateProvider:
some_domain.com/abc/pqr/xyz
Issue is the number of levels after "some_domain.com" can vary. It can be like
some_domain.com/abc/pqr/xyz
some_domain.com/abc/pqr
some_domain.com/abc
some_domain.com/abc/pqr/xyz/1234
tried the many approaches for this in the state definition:
$stateProvider
.state('dummy', {
url: '/*',
templateUrl: 'views/home.html',
controller: 'LandingPage'
});
}]);
Can anybody help me regarding this?
As the parameters you are talking about are part of the route itself, so you cannot have a single route to handle all these cases. I can think of 2 ways to go about it :
Create a seperate route for each case.
Use optional parameters if you can modify the logic accordingly. If the parameters can be optional, they should sent as query parameters instead of making them part of URL as such. So, the URL becomes something like :
url: '/dummy?param1?param2?param3'

dynamic routing in ui-router in angularjs and change the url

I write an application with angularjs and use ui router for dynamic routing , my app has a page for display list of news and when click on a news , Explanation of the news is showing
for example if I have a news with id=3 when i click on link of this news the url change to news/3 and when click on a news with id=5 url change to news/4 but i want to change url to news/subnews/third or news/subnews/fifth
my piece of code for change url and content is like this
.state('news', {
abstract:true ,
url: "/news",
templateUrl: "views/news/news.html",
})
.state('news.showAll', {
url: "",
templateUrl: "views/news/showAllNews.html",
})
.state( 'news.detail',{
url:"/:newsId",
templateUrl: "views/news/tmpShowDet.html",
controller:"newsShowing",
resolve:{
newsId: ['$stateParams', function($stateParams,newsId){
return $stateParams.newsId;
}]
}
})
what is the true way for display like news/subnews/....
How many 'subnews' do you want?
Translating numbers to words can get a little tricky, and spoken-language specific. Example: at 'subnews/101' do you want 'subnews/onehundredandone or subnews/onehundredandfirst or subnews/oneohone'.
I would recommend, if you only have a few subnews possibilities, going by categories.In that case, it seems you already know how to implement, or have access to the documentation for UrlRouteProvider.
If you have many subnews, I would leave the parameter as an integer, which is relatively spoken-language agnostic. You can always mask it or build a lookup table, etc if you don't want it displayed.
Speaking of which, if you still want to change the integer to a word, just use a lookup, and the url docs.
Cheers, bro

Multiple optional parameters in Angular.js

I typically use querystrings for filtering results, eg:
URL: /Events/List?type=art&city=miami&life=present
I can put them in any order and get the same results, eg:
URL: /Events/List?city=miami&life=present&type=art
URL: /Events/List?life=present&type=art&city=miami
I can also make them optional, eg:
URL: /Events/List?type=art,
or: /Events/List?type=art&life=&city=
Question: How can I achieve this same "effect" with Angular.js routes? given the fact that parameters are passed all in a "RESTful" way in Angular
I was thinking in something like this:
URL: /Events/List/city/miami/life/present/type/art
Which I can achieve with a route like this:
.when('/Events/List/city/:city?/life/:life?/type/:type?', { ... }
But I already see many problems:
Order of parameters is important (I would have to define many times the route?)
Optional parameters will give a non intuitive URL,
eg: /Events/List/city/life/type/art,
and this is not the case in optional querystrings (they are more intuitive to read I think): eg: /Events/List/?city=&life=&type=art
If you want to use query strings angular has $location.search() that is both a setter and getter.
The difference between angular search and window version location.search is the query falls after the url hash and when setting or getting it uses objects rather than strings
See Using $location in developer's guide
You can inject $routeParams into your controller. Here's an example from the docs:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
http://docs.angularjs.org/api/ngRoute.$routeParams
I recently encountered a similar need (the ability to grab an unknown quantity of arguments off the path), and had started off by looking at $routeProvider. I ultimately abandoned that effort in favor of ui.router.
The most powerful (but possibly also tedious) approach for you would be to work with regex parameters. Consider the following (a snippet from some code I'm currently authoring):
$stateProvider
.state("list", {
url: "/",
controller: "PluginsListController",
templateUrl: "PluginsList.html"
})
.state("path", {
url: "/{plugin}/*path",
controller: "PluginDetailsController",
templateUrl: "PluginDetails.html"
})
;
The second state accepts two positional parameters: a plugin and a path. The path argument is a wildcard, that grabs everything after the immediately preceding slash. The idea here is that I can specify something like http://www.myfirsturl.com/app/MyFirstPlugin/level1/level2/level2.php, and end up with "MyFirstPlugin" in $stateParams["plugin"] and "level1/level2/level2.php" in $stateParams["path"]. It's up to the application logic to handle the long path parameter (and you would be likewise responsible for consuming this variable-length argument), but this approach does allow you to write a single state handler for an unknown number of url paths.

Passing additional parameters using $routeProvider

In my AngularJS app I have one template and one controller that I can reach via 2 different url:
$routeProvider.when('/site/contents/:obj/:parent/:isnew?', {
templateUrl: '/partials/site/data.html',
resolve: {
loggedin: checkLoggedin
}
});
$routeProvider.when('/site/contents/new-obj', {
templateUrl: '/partials/site/data.html',
resolve: {
loggedin: checkLoggedin
}
});
The second route should statically set a parameter isnew=1, as I would do using a RewriteRule in apache, but looking at the documentation https://docs.angularjs.org/api/ngRoute/provider/$routeProvider it seems impossible to do.
Anyone had encountered the same question?
You can't really set default route parameters in Angular, if that is what you are trying to do.
The best idea would probably be to check in your controller if $routeParams.isnew is set and, if not, default it to 1.
Angular routes are supposed to be fairly simple rather than being heavily pattern based like RewriteEngine in apache, so the logic should be in your controller.
Your controller could look like so:
function($routeParams) {
$scope.isNew = ($routeParams.isnew || 1);
}
In your case, you can probably even get away with having no isnew param. Use the first route for modifying existing objects and the second for creating them (so the existence of obj in the params defines if it is new or not).

AngularJS: multiple edit forms routing?

I have a listing of Requests each with a Request_Type_Id which maps to a feeder list (which could grow as the application evolves). For example, we might have (id, request_type) 1 - Sales Information, 2 - Technical Support, 3 - Order Information and, of course, each one has unique fields so the edit forms are very different.
By clicking the name, I want to open the correct of these different edit forms.
For routing, I have this:
$routeProvider
.when('/editrequest/:req_id/:id', {
controller: 'EditRequestController',
templateUrl: '/App/Views/editRequest.html'
}).otherwise( { redirectTo: '/' } );
because I set the edit link to
{{req.title}}
I am still trying to learn AngularJS and am wondering if the best way to proceed from here would be to choose the correct edit form on /App/Views/editRequest.html by using ng-show. This would mean there would be at least 3 forms on that template (not nested, though) which might be problems in some browsers.
Is there a more AngularJS way to do this that I haven't learned yet?
Thanks in advance!
templateUrl can be a string or a function, which accepts route parameters and return a string.
In your case, you can doing so:
$routeProvider
.when('/editrequest/:req_id/:id', {
controller: 'EditRequestController',
templateUrl: function(params) {
// use params.req_id to generate a url
return '/App/Views/editRequest'+params.req_id+'.html';
}
}).otherwise( { redirectTo: '/' } );
Another important thing worth mention here is, be careful when use interpolate in href or src. Use ng-href or ng-src instead.

Resources