How to get URL segment in Angular JS? - angularjs

I have URL's in project as:
http://blo.c/news
http://blo.c/video
How I can get segments news, video from these URL?
I tried to use $location in Angular JS, but this object has not these segments

You need to use $location.path()
// given url http://blo.c/news
var path = $location.path();
// => "/news"
If you are using HTML5 mode you must ensure $locationProvider.html5Mode(true) is set so $location works properly.
If you are not using HTML5 mode (which is the case here); then you'll need to drop to traditional javascript to get the URL, since you are not using Angular routing in the first place:
// given url http://blo.c/news
var path = window.location.pathname;
// => "/news"
You might choose to inject $window instead of using window directly, this is only a thin wrapper over the native window object but facilitates testing.

Use the $location.path function to get the url. To get what's after the url, use split
$location.path.split(/\{1}/)[1]

const URL = '/seg1/?key=value';
$location.path();// will return URI segment (in above URL it returns /seg1 ).
$location.search(); // getter will fetch URL segment after ? symbol.
//(in above URL it returns {key:value} object ).
Official Doc: https://docs.angularjs.org/guide/$location

Related

Angular RouterUI $location.search() vs $stateParams

With the use of Angular UI Router - you can access parameters url using $stateParams. Additionally, the $location service also has a way to access URL parameters: $location.search().param1
I know that sometimes there is an advantage in using $location.search() to retrieve values in the URL.
For example, when changing the URL without reloading state. Example snippet:
$state.current.reloadOnSearch = false;
$location.search('param1', 'new value').replace();
$timeout(function () {
$state.current.reloadOnSearch = undefined;
});
In this case, the URL gets changed with new parameter param1 - if I try to use $stateParams.param1 - its undefined. Meaning, $stateParams doesn't know about that change. In such a scenario, I use $location.search().param1 to get the updated value.
So as you can see, sometimes $location.search() has an advantage over $stateParams.
What are the disadvantages? Can't I just always use $location.search() and not use $stateParams? Is there any advantage in using $stateParams? What situations?

Angular 1.5 skip nav overridden by router

I have an Angular 1.5 app that needs to be accessible. I've added a skipnav i.e:
Skip navigation
however this is being overridden by:
$urlRouterProvider
.otherwise(function ($injector, $location) {
var state = $injector.get('$state');
state.go('404');
return $location.path();
});
How can I set the focus on the #content area?
First of all - The documentation states that the arameter is The url path you want to redirect to or a function rule that returns the url path. The function version is passed two params: $injector and $location.
So you're redirecting to the 404 state and return the location path which return only the current path without any parameters nor the hash.
What you need to do is to set the hash first (in case it's not already presented in the URL or the url contain a different hash):
$location.hash('content');
And then, return the absolute url with all segments:
return $location.absUrl();
There is a chance that you could just return; without returning any path, because just by setting $location.absUrl() will make angular focus the #content element. Not sure about it, but you can try and see if it's working for you.

angular routeparams empty on api callback

Im trying to get some paramters from the urlcallback coming from an external authentication, in my angular projct using angular-route/$routeProvider
the api redirects to:
http://localhost:8080/dist/?somevar=someval&val2=someotherval#/
Note the params come before #/
I try to read the get values with $routesparams like:"
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
console.log($routeParams.somevar);
console.log($routeParams);
});
This returns an emptyresult. however it i change the url to:
http://localhost:8080/dist/#/?somevar=someval&val2=someotherval
it works, with the api I can give a callback url and I set it like:
?callbackUrl=http://localhost:8080/dist/#/
How should I get these parameters from the url whithout changing the callback url?
In this case, the problem is with the Hashbang mode, which has a hashPrefix #. In the configuration phase, you have to enable html5Mode $locationProvider.html5Mode(true);
But this requires URL rewriting on server side and the HTML <base> tag.
Read more here: https://docs.angularjs.org/guide/$location
So the explanation why it does not work for you this way, is when you give the http://localhost:8080/dist/?somevar=someval&val2=someotherval#/ url to angular, it looks for the parameters after the #, and when you populate the $routeParams, it will create the parameters after the #.

How to prevent Angular from turning URL hash into a path

I have an angular app with a number of links. Clicking each link displays a particular set of data. I would like each link to set a hash in the URL, like http://foo.com/bar#item1, and I'd also like to show the page with the particular set of data displaying when that URL with the hash is accessed directly.
I was hoping to do it by reading / manipulating the $location.hash(), but as soon as I inject $location into my controller, the #item1 in the URL changes to #/item1. Is there a way to prevent Angular from doing this, and what's the best way of setting up what I described?
You could pass parameters in the routes /bar/item1, catch it with $routeParams and if exist make $location.hash().
"controller"
var anchor = $routeParams.anchorBottom;
if(anchor){
$location.hash(anchor);
$anchorScroll();
}
"link to section"
$location.path('/heart/bottom');
"route"
.when('/heart/:anchorBottom',{
You could see this running here.

AngularJS - How can I do a redirect with a full page load?

I want to do a redirect that does a full page reload so that the cookies from my web server are refreshed when the page loads. window.location = "/#/Next" and window.location.href = "/#/Next" don't work, they do an Angular route which does not hit the server.
What is the correct way to make a full server request within an Angular controller?
For <a> tags:
You need to stick target="_self" on your <a> tag
There are three cases where AngularJS will perform a full page reload:
Links that contain target element
Example: link
Absolute links that go to a different domain
Example: link
Links starting with '/' that lead to a different base path when base is defined
Example: link
Using javascript:
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API: $window.location.href.
See:
https://docs.angularjs.org/guide/$location
https://docs.angularjs.org/api/ng/service/$location
We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:
If needed, virtually alter current URL through $location service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location helper methods. E.g. we ran $location.search(..., ...) to just change value of a querystring paramater.
Build up the new destination URL, using current $location.url() if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:
http://yourdomain.example/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en
then you should set URL as in:
var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';
(with the leading '/' as well).
Assign new destination URL at low-level: $window.location.href = destinationUrl;
Force reload, still at low-level: $window.location.reload();
After searching and giving hit and trial session I am able to solove it by first specifying url like
$window.location.href = '/#/home/stats';
then reload
$window.location.reload();
I had the same issue. When I use window.location, $window.location or even <a href="..." target="_self"> the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload() after window.location to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:
$scope.openPage = function (pageName) {
window.location = '#/html/pages/' + pageName;
window.location.reload();
};
Try this
$window.location.href="#page-name";
$window.location.reload();

Resources