AngularJs $location.path with full url - angularjs

I want to route the user to an url if he clicks ok in a modal. In my controller i receive urls like
var newUrl = http://localhost:3000/#/dashboard
var newUrl = http://localhost:3000/#/users
as variable.
If i then use
$location.path(newUrl);
it does not work. I also tried
$location.url(newUrl);
but my URL gets encoded like this.
http://localhost:3000/#/#%2Fdashboard
Is there a way to get only the path of the url?
Edit
this code is part of a service. A user make some inputs in a form and clicks on another link for example in the menu. Then a popup appears where he is asked to skip his form changes. If he clicks yes i get the requested url. This is from my development environment on the server of course it will be another url. So i can not just use
$location.path("/users")
for example

I ran into this same problem when having Angular preventDefault $locationChangeStart events, force a save, and only redirect upon success. I define the following function in the body of the controller:
var baseLen = $location.absUrl().length - $location.url().length;
function getPath(fullUrl) {
return fullUrl.substring(baseLen);
}
It doesn't seem like a clean solution, but as a work around, it does the job. A RegEx might work better for you, if you don't know that your URLs are pointing to the same site.

You can use $location.absUrl().
See the official documentation: enter link description here
This method is getter only.
Return full url representation with all segments encoded according to rules specified in RFC 3986.

May I offer a different solution:
$scope.$on('$locationChangeStart', function(e) {
if (meetsTheRequirementsToLeave()) {
return;
}
var newPath = $location.path();
e.preventDefault();
checkIfUserWantsToLeave().then(function() {
$location.path(newPath);
});
});
Within this event $location.path() returns the new path.

Related

How can I close the InAppBrowser automatically when specific content is returned?

How can I automatically close the $cordovaInAppBrowser when it goes to my website and returns content "OK"? I would like to do this to avoid displaying the close button in the browser window.
Does anyone know how I can achieve this?
I did find the website that can solve this for those who also need to self close the browser in some condition.Here is the reference link : https://developer.salesforce.com/forums/?id=906F00000009ALSIA2
sample coding:
authWindow.addEventListener('loadstop', function(e) {
var loc = e.url;
//when url is changed check if the url contains your specific callbackURL
if (loc.search(data.callbackURL) >= 0) {
//at this point close your inapp browser
//you will land on the index page within your application.
authWindow.close();
//your code after successful authentication
}
});
you can use something like a timeout function or other than that a even listener other than i would suggest make a custom plugin and use it. The solution provided by #Blouraf is very hacky.
I did find some documentation on the cordova plugin that recommends a listener.

How do I set $stateParams by using url parameters using uiRouter in Plunker?

I'm trying to demonstrate something using url-query parameters using plunker, but I can't even get the parameters to show up (and then consequently not demonstrate my original issue).
I have created a simple plunker where the states url property looks like this: url: '/root?firstParam'
What I want then is to populate $stateParams.firstParam with whatever I write in the url of the browser for that queryParameter.
Plunker, plunkerWithParameter?firstParam=foo
I would imagine that $stateParams.firstParam would be undefined for the first url, but set to "foo" for the second. But it's undefined in both cases.
How can I get the $stateParams.firstParam to be set?
Edit: It seems that it is actually possible (#Rogerio Soares answer proves this). Keeping my answer here because there was an other error in the code.
There is no way to get the parameters from the browsers search bar in a Plnkr app since it is running in an iFrame. I fixed another problem of yours below:
I added the parameter to your otherwise statement like this:
$urlRouterProvider.otherwise('/root?firstParam=test');
The problem is that you redirected to root when no other route was found, and you didn't specify any parameters to the route.
Updated PlunkR: https://plnkr.co/edit/OxEGVkhzBO332ym3q8fV?p=preview
my two cents : As #Johannes Ferner said Plunker use iframe, but you can at least get your url with document.referrer
It is a little hacky but it work :D
$scope.parameters = [];
var url = document.referrer;
var props = url.split("?")[1]
.split("&")
.map(function(o){
return o.split("=");
});
console.log(props);
for(var i = 0; i < props.length; i++){
var prop = props[i];
console.log(prop);
if($stateParams.hasOwnProperty(prop[0])){
$scope.parameters.push({name: prop[0], value:prop[1]});
}
}
https://plnkr.co/edit/Cejgj1cLJnwQT2LzjsRm?firstParam=foo&p=preview
the Problem is that the plnkr is running within iFrames, so the URL you tried is simply wrong.
Try this one:
https://plnkr.co/edit/jV2pdV6q8g8QZ132Qu3A
I have added a Link to your root state with the first-parameter set to 'Yeah' like this:
<a ui-sref="root({firstParam: 'YEAH'})">Go to Root with Firstparam = "YEAH"</a>
Which results to this URL: https://run.plnkr.co/roo/root?firstParam=YEAH.
Wrong: If you open this URL directly in the browser, the query-params are correctly passed to your AngularJS Application and set to $stateParams.firstParam
Correct: I did not found a way to have a permanent URL to the plnkr without the code being embedded in an iframe.

How to append url to the end of a button link in angularjs?

Assuming I am currently on the page:
www.mysite.com/root/#/?page=orderpage
On the page, I have a link:
Click Here for Mobile
I want to make it such that when the user clicks on the "Click Here For Mobile" link, I can take the user to:
www.mysite.com/root/mobile/#/?page=orderpage
Notice that the URL is similar to what it was before (preserving whatever parameters were there), except there is a "mobile" in between the root and the #.
How do I make it such that the "Click Here For Mobile" link will have the redirect to the appropriate URL as described above?
Is it good practice to do this? Examples appreciated.
As Ajay said, client-side routing will not be possible in this case.
So what you're left with is either doing (like Ajay said):
<a target="_self" href="/root/mobile/#/?page=orderpage">
Or, you could define a function (in a service, in the specified controller, or someplace else where you have access to it) that takes a string and changes the $window.location.href (this will result in a page reload).
Something like this:
app.controller("SomeCtrl", function ($scope, $location, $window) {
$scope.changeUrl = function (url) {
var newUrl = $location.$$absUrl.replace("/#/", url);
$window.location.href = newUrl;
};
});
And then in your html you would use:
Go mobile
Without Javascript enabled (which I'm assuming you're not gonna be supporting with an Angular app) this would not take you anywhere. In that case, Ajay's solution is definately the prefered one.
The benefit of turning it into a function is that all you have to pass is what you're changing before the "/#/".
Good luck :)

Backbone.js change url without reloading the page

I have a site that has a user page. On that page, there are several links that let you explore the user's profile. I'd like to make it so that, when one of those links is clicked on, the url changes, but the top third of the page containing the user's banner doesn't reload.
I'm using Backbone.js
I have a feeling that I'm in one of those situation where I have such a poor understanding of the problem I'm dealing with that I'm asking the wrong question, so please let me know if that appears to be the case
My mistake was assuming that there was a special, built-in way of doing this in backbone. There isn't.
Simply running the following line of code
window.history.pushState('object or string', 'Title', '/new-url');
will cause your browser's URL to change without reloading the page. You can open up the javascript console in your browser right now and try it with this page. This article explains how it works in more detail (as noted in this SO post).
Now I've just bound the following event to the document object (I'm running a single page site):
bindEvents: () ->
$(document).on('click', 'a', #pushstateClick)
pushstateClick: (e) ->
href = e.target.href || $(e.target).parents('a')[0].href
if MyApp.isOutsideLink(href) == false
if e.metaKey
#don't do anything if the user is holding down ctrl or cmd;
#let the link open up in a new tab
else
e.preventDefault()
window.history.pushState('', '', href);
Backbone.history.checkUrl()
See this post for more info.
Note that you CAN pass the option pushstate: true to your call to Backbone.history.start(), but this merely makes it so that navigating directly to a certain page (e.g. example.com/exampleuser/followers) will trigger a backbone route rather than simply leading to nowhere.
Routers are your friend in this situation. Basically, create a router that has several different routes. Your routes will call different views. These views will just affect the portions of the page that you define. I'm not sure if this video will help, but it may give you some idea of how routers interact with the page: http://www.youtube.com/watch?v=T4iPnh-qago
Here's a rudimentary example:
myapp.Router = Backbone.Router.extend({
routes: {
'link1': 'dosomething1',
'link2': 'dosomething2',
'link3': 'dosomething3'
},
dosomething1: function() {
new myapp.MyView();
},
dosomething2: function() {
new myapp.MyView2();
},
dosomething3: function() {
new myapp.MyView3();
}
});
Then your url will look like this: www.mydomain.com/#link1.
Also, because <a href=''></a> tags will automatically call a page refresh, make sure you are calling .preventDefault(); on them if you don't want the page to refresh.

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