How do I parse the location path in AngularJS? - angularjs

For example the page is 'http://mywebsite/details/555', how can I get that '555' out of there in my controller? It's not a parameter, so I cannot look up for it by name.

Have a look at the Angular routing parameters. The number you want is actually and id used in the routing path which you can catch:
https://angular.io/guide/router
https://angular-2-training-book.rangle.io/handout/routing/routeparams.html

Your are writing that 555 is not a parameter - but I think you want to use it like a parameter. Parameters look like: http://mywebsite/#/details/555
You can then define this in your router (here I'm using ui-router, but you can do the same with ng-route:
$stateProvider
.state('details.id', {
url: "/details/:id",
templateUrl: 'detail.html',
controller: myController
})
See https://github.com/angular-ui/ui-router/wiki/URL-Routing
If you still want to parse your URL string, you can do it this way:
var detailId = this.href.substr(this.href.lastIndexOf('/') + 1);
But the right (and probably the only working) way is to use the router for that.

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'

Angular removing anything after '=' in query string from URL

I am trying to get query strings to work in my Angular setup, but it is behaving weirdly.
When i go to a URL like this:
http://localhost:3000/?query=test
The URL changes and removes anything after the '=' to end up with:
http://localhost:3000/?query
Has anyone had this problem before?
I am currently using Angular UI Router with defined states and HTML 5 mode. I have also tried specifying the query parameter in the route as below:
.state('home', {
url: '/?referrer',
templateUrl: 'app/views/home/home.html',
controller: 'mainController'
})
UPDATED........
OK. In my controller i had this:
var referrerURL = $location.search('referrer');
Removing this, fixes the issue. Why would this cause the problem?
For $location.search() method, you should use it like this:
$location.search('key','value').
If you don't set the value, it would be "true" by default.
More information here
Thanks for all your input.
I fixed this by changing my controller to use:
var referrerURL = $location.search().referrer;

Create Angular Dynamic Route

I have a route string like the following var global_book_route = /books/:id specified in a variable.
I want to be able to use $route or $location to deep link to this route in a controller, is there a way to do this without re-specifying the url prefix?
This would work: var id=1; $location.path('books/'+id') -> '/books/1'
However, this does not: $location.path(global_book_route).search({id:1}) -> 'books/:id?id=1'
Is there a way I can use the route specified in the string to go to the correct location?
I think you are mixing up the route itself (/books/:id) with the representation of the route in your code.
For example, your global_book_route should be only "/books/".
Then, if you want to load a specific book, you can go the the location global_book_route + book_id as long as the route is declared in your code, like:
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
}
})
On a side node, when dealing with routes in Angular, it's really worth it to look into angular-ui, the ui-router offers a way better system to manage your routes and states.

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.

how to pass querystring in angular routes?

I am working with AngularJS routes, and am trying to see how to work with query strings (for example, url.com?key=value). Angular doesn't understand the route which contains key-value pair for the same name albums:
angular.module('myApp', ['myApp.directives', 'myApp.services']).config(
['$routeProvider', function($routeProvider) {
$routeProvider.
when('/albums', {templateUrl: 'albums.html', controller: albumsCtrl}).
when('/albums?:album_id', {templateUrl: 'album_images.html', controller: albumsCtrl}).
otherwise({redirectTo: '/home'});
}],
['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode = true;
}]
);
It is correct that routes do not work with query strings, however that doesn't mean you can't use query strings to pass data between pages when switching routes! The glaring limitation with route parameters is that they can't be updated without reloading the page. Sometimes this isn't desired, for instance after saving a new record. The original route parameter was a 0 (to signify a new record), and now you want to update it with the correct ID returned through ajax so that if the user refreshes the page they see their newly saved record. There is no way to do this with route parameters, but this can be accomplished by using query strings instead.
The secret is not to include the query string when changing the route, because that will cause it not to match the route template. What you can do is change the route and then apply the query string parameters. Basically
$location.path('/RouteTemplateName').search('queryStringKey', value).search( ...
The beauty here is that the $routeParams service treats query string values identically to real route parameters, so you won't even have to update your code to handle them differently. Now you can update the parameters without reloading the page by including reloadOnSearch: false in your route definition.
I don't think routes work with query strings. Instead of url.com?key=value can you use a more RESTful URL like url.com/key/value? Then you would define your routes as follows:
.when('/albums', ...)
.when('/albums/id/:album_id', ...)
or maybe
.when('/albums', ...)
.when('/albums/:album_id', ...)
You could look at the search method in $location (docs). It allows you to add some keys/values to the URL.
For example, $location.search({"a":"b"}); will return this URL: http://www.example.com/base/path?a=b.
use route params
var Ctrl = function($scope, $params) {
if($params.filtered) {
//make sure that the ID is there and use a different URL for the JSON data
}
else {
//use the URL for JSON data that fetches all the data
}
};
Ctrl.$inject = ['$scope', '$routeParams'];
http://docs.angularjs.org/api/ng.$routeParams
I can only think of two usecases for the querystring in URL:
1) If you need the key/value pair of your querystring in your controller (eg. to print Hello {{name}} and get the name in querystring such as ?name=John), then as Francios said just use $location.search and you will get the querystring as an object ({name:John}) which you can then use by putting it in scope or something (e.g. $scope.name = location.search().name;).
If you need to redirect to another page in your router based on what is given in the querystring, like (?page=Thatpage.htm) then create a redirectTo: in your routerProvider.when() and it will receive the search object as its third parameter. look at 2:10 of the following EggHead Video:
http://www.thinkster.io/pick/SzcF8bGeVy/angularjs-redirectto
basically, redirectTo:function(routeParams,path, search){return search.page}

Resources