Prevent route interpretation when adding parameters to URL - javascript

In my AngularJS application I have the following routing mechanism:
$routeProvider.when('/questions',
route.resolve('questions',
'questions/',
'questions',
'overview',
access.authorizedAccess))
This works correctly, hitting a URL like domain.com/app/#/questions loading the correct controller and template.
What I want to do is have the option to add parameters to the current URL without triggering a page reload (basically reinterpreting the URL). The problem that I have now is that by doing window.location.hash = '#/questions?query=test'; the route is reinterpreted causing a page reload.
What I have tried to do was this:
$rootScope.$on("$locationChangeStart", function (event, next, current) {
if (next.indexOf('?') > -1)
event.preventDefault();
});
This indeed does not trigger a route reinterpretation, but it removes the parameter from my hash, turning it back into '/questions'.

Can your try the option reloadOnSearch:false during intitializing the routes in $routeProvider. See the documentation here

Related

Get Information from one page to another with angular routing

Image a page, that page is called "dashboard". In the dashboard, there is a drop-down menu, with items, which are listed by the PHP script, and their count varies on the number of results from a database.
Now, when a user clicks one of the items from the menu, it should redirect him to the configuration page, with some data (id, type). Sounds simple, but the redirecting method used is made with angular, so it uses URL hashing, without refreshing the site. URL of configuration page then looks like:
https://www.example.com/index.php#/configure
...and I want to get there some data. The site we see there is just a blank site, which, in the file tree, is named "configuration.php", but you don't see it in the URL, because of angular code in "configure.module.js.php", which simply redirects the user, gives them the right site with:
(function () {
'use strict';
angular.module('BlurAdmin.pages.configure', [])
.config(routeConfig);
/** #ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('configure', {
url: '/configure',
title: 'Configuration',
templateUrl: 'app/pages/configure/configure.php',
controller: 'addCtrl',
});
}
})();
So I assume, that if I want to get the data to my site, I need some kind of a GET request. I figured out, that it will work if I use the GET request like so:
https://www.example.com/index.php?something=works&omg=itWorks#/configure
So my index.php will work with the GET data and write them to a SESSION, which can then be used in configuration.php!
Well, it works, kinda... But the main thing is, that it is all angular, so NO SITE REFRESH AT ALL! That means none of my files will be refreshed, so after I click the button again, the site will not get the GET request again, it will simply redirect me to configuration.php, without dealing with the new data... It will keep the first GET parameters and SESSION.
So there goes my question. how to make it? I really need that one click to send that data to configuration.php, without refreshing the site, but, working and updating.
In html you add ui-sref to like this
ui-sref="configure/({id: valueid})
in file config
url:'/configure/:id'
in your controller add $stateParams like this
function addCtrl($scope,$http,$stateParams)
and use ajax to GET
var params = $.param({'id':$stateParams.id})
$http({
method:'GET',
url:'yoururl?id=' + $stateParams.id,
data:params,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess);

ui-router url parameter with hashtag

I'm working on the routing of my angular application, but I can't seem to find the following:
example.com/#parameter
In this url the #parameter should stay #parameter and get the param data. Now it removes the # and goes to example.com/parameter
If I go to example.com/#parameter it should do the same as it would if I go to example.com/parameter
I have the following in my app.js
url: "/:bandName"
and send this data to my controller with $stateParams
Is there any way to keep the hashtag in the url ?
-- edit
so here is some code that works on enter with /#parameter
$urlRouterProvider.when(':#bandName', '/:bandName')
.otherwise('/');
$stateProvider.state('appband', {
url: "/:bandName",
templateUrl: "main.php",
controller: 'mainController'
})
$locationProvider.html5Mode(true);
With this if I go to example.com/#randomBandName I get redirected to example.com/randomBandNameand I get randomBandName as parameter in my controller
So what I need is on enter that example.com/#randomBandName stays example.com/#randomBandName and that I still get randomBandName in my controller.
But when I remove $urlRouterProvider.when(':#bandName', '/:bandName') I just get an empty page.
There are a few things that look suspect with this:
trailing slash
Are you using HTML5 mode for your URLs? I'd suggest using this URL setup url: "/parameter" if you indeed see param as more of a resource.
You might also read this - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-make-a-trailing-slash-optional-for-all-routes
query param
If you are intending param to be a query parameter then you need this..
url: "/?parameter"
more on that here - https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters

Backbone form submit routing

Is it possible to have a Router implementation similar to the following?
var Router = Backbone.Router.extend({
routes: {
'' : 'search',
'*querystring' : 'results'
},
search: function() {
// load search view
},
results: function(querystring) {
// load search view
// make ajax request using querystring
}
});
The search view has a form that when submitted should go to the results view which will parse the url for the query, submit an ajax request and then display the response.
Obviously something like this would make more sense
'results?*querystring' : 'results'
But I can't get my form to submit the URL in that format.
When put my form action as <form action="index.html/results"> I get http://localhost:8000/index.html/results?c=foo&a=bar as my URL.
This is close, but I really need http://localhost:8000/index.html#/results?c=foo&a=bar and when I try to do this with <form action="index.html#/results"> it gives me http://localhost:8000/index.html?c=foo&a=bar#/results which is not what I want :(
This is why I would rather just have no form action and instead have a route that can will parse the query if one exists.
Ok thanks for reading. Hopefully someone understands some of that and can help me out.
don't put pushstate to true, set it to false
Backbone.js PushStates: Fallback for Internet Explorer not working
Remove form or prevent the submission
Simply get the params and trigger a route
Handle the params appropriately in the triggered route.
Router
routes:{
'search':'search' //queryString is automatically passed as last param in backbone 1.1
},
search: function(queryString){
//Write your logic to do the search
}
View:
events:{
'submit form':'preventAndNavigate'
},
preventAndNavigate: function(e){
e.preventDefault();
var query = $(e.currentTarget).serialize();
Backbone.history.navigate('search?'+query,{trigger:true});
}
Docs :
Backbone Routers now handle query params in route fragments, passing them into the handler as the last argument. Routes specified as strings should no longer include the query string ('foo?:query' should be 'foo').
References :
http://backbonejs.org/#changelog

Reload page on browser back/forward button in AngularJS with ui router

I have the following config for ui router state in my angularjs app.
$locationProvider.html5Mode(true);
$stateProvider
.state('index', {
url: '/index?zoom&center',
views: {
'map': {
controller: 'MapCtrl',
templateUrl: 'map.html'
}
},
reloadOnSearch:false
});
However, the back forward button in the browser go to different url, but I need to reload the page with the urls as stateParams.
For example:
User1 go to page http://www.example.com/index?zoom=2&center=1,2.
then he does bunch operation in the page, the url becomes http://www.example.com/index?zoom=12&center=3,4
Then he presses the back button, the url changes to the previous one, but I need to reload my page to let the controller read the query parameters to do the right thing...
Any way to let it work with browser back/forward?
Have you tried setting reloadOnSearch to true? If that doesn't suite your needs, perhaps check out this question: Force AngularJS to reload a route although option reloadOnSearch is set to false
A simpler alternative may be to just force the reload with window.location = newUrl whenever necessary.

Changing routes doesn't refresh data, gives ng:areq error

In my AngularJS app, I have a route that looks like:
.when('/:project/:page', {
templateUrl: '/ui-editor/editor',
controller: 'EditorCtrl'
})
In a view, I have a link that looks like:
Next page
When I click that link in my app, the URL in the browser changes correctly (e.g. /myproject/1 to /myproject/2), but I get an error Error: [ng:areq] Argument 'scope' is required. The line that the error refers to is the console.log statement in:
socket.on('ws:init-data', function(data) {
console.log('on ws:init-data', data);
// Handle incoming data from server
//...
});
If I refresh my browser, the correct data loads as it should for /myproject/2.
use ng-href is better. It can avoid link be clicked before angular parse.
<a ng-href="/{{currentProjectId}}/{{currentPageId + 1}}">Next page</a>
I don't know the exact cause about this error, but I have a suggestion:
use $location to change your url.
you can see on the dev_guide:
When should I use $location?
Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.
http://docs.angularjs.org/guide/dev_guide.services.$location

Categories