How to replace "#" routes to standard routes - backbone.js

E.g:
in router.js
routes: { "": "home", "first": "first" }, .....
in page:
home link first page
In the browser address bar: www.domain.com/#first
I want to get URL: www.domain.com/first
How to replace the "#" in routes?

You can use Backbone.history.start({ pushState: true }).
From documentation (http://backbonejs.org/#History):
To indicate that you'd like to use HTML5 pushState support in your
application, use Backbone.history.start({pushState: true}). If you'd
like to use pushState, but have browsers that don't support it
natively use full page refreshes instead, you can add {hashChange:
false} to the options.

Related

$state.href with absolute: true doesn't return the right url

I'm using Angular and UI router. I'm trying to get a link shown on the page that the user can copy and share. This thread has shown me that $state.href is the function I'm looking for, however it isn't generating the correct link.
An important detail here is that the root of my application is not the root of the domain. In this case, the domain is localhost, but the root of the angular app is in localhost/dev/app/.
Here's the command I'm using inside my controller.
$scope.url = $state.href('survey', { survey: "asd" }, {absolute: true});
In my app.js, the following route is declared:
.state('survey', {
url: "/:survey/survey?ao",
templateUrl: "views/survey/survey.html",
controller: "surveyController",
},
data: {
requireLogin: false,
requireAdmin: false
}})
This should return http://localhost/dev/app/#/asd/survey, instead it returns http://localhost/#/asd/survey.
(The remarkable thing is that ui-sref="survey({survey: "asd"}) does translate to the correct link.)
Is there a way I can fix this so I get the full url?
Adding a base tag to my app page solved this issue for me. It defines the base URL for the page with the router references. For legacy support reasons, I'm on version 0.2.15 of Angular UI Router. I don't know if this is still necessary for more current versions.
<base href="http://localhost/dev/app/" />
.state('survey', {
url: "/:survey/survey?ao",
templateUrl: "views/survey/survey.html",
controller: "surveyController",
data: {
requireLogin: false,
requireAdmin: false
}
})
You had an extra '},' in after controller, maybe that is messing things up? Also if you're passing parameters you might want to include that as a params line:
params: {
survey: null
}
Also if you want the url http://localhost/dev/app/#/asd/survey your url should be:
url: "dev/app/:survey/asd/survey"

Angular UI Router: How to go to the same state with different $stateParam?

I am wondering how can I go to the same state, with different $stateParam?
I was trying to go with:
$state.go('^.currentState({param: 0})')
However, it was not working.
the params are second paramater of the go() method
$state.go('^.currentState', {param: 0})
go(to, params, options)
Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states).
You might want to use this piece of code:
<a ui-sref=".({param: 0})"></a>
No need to use controller.
In my case, I wanted to reload the same state, but with different parameters. (null in this specific occurrence)
The situation is as follows: We have a website with different companies, each with their own branding page. You can visit other companies' pages and there's a menu entry to quickly visit your own.
A company's page is located under /company/somecompanyid, whereas your own page will be loaded when visiting /company. Without the addition of an id. Or company_id: null in code.
The problem
When you're viewing a random company's page, let's say company/123456 and you click the designated menu entry to visit your own page, nothing would happen!
Ui-router believes you're on the same route and simply keeps you there.
The solution
Add the following to your template:
<a ui-sref="company" ui-sref-opts="{reload: true, inherit: false}" ... ></a>
What does it do?
reload: true This will force your state to reload. But it'll copy your current route parameters. Which means your still seeing the other company's page.
inherit: false Setting the inherit property to false will force ui-router to use the params you provided. In my case, the companyId was null and user's personal page was loaded. Hurray!
You can find all ui-sref-options on the documentation pages. ui-sref-options
If you'd like to reload your state, you can also use ui-sref-opts. Passing in the reload: true option, will reload the current state.
<a ui-sref-opts="{reload:true}" ui-sref="app.post.applicants">Applicants</a>
The simplest solution is ->
You can make 2 state with same controller and same html page and redirect one by one
PROS: No need to handle back history and all works with the great flow
.state('app.productDetails', {
url: '/productDetails',
cache: false,
views: {
'menuContent': {
templateUrl: 'src/products/productDetails/productDetails.html',
controller: 'ProductDetailsCtrl'
}
},
params: {
productID: 0,
modelID: 0
}
})
.state('app.modelDetails', {
url: '/modelDetails',
cache: false,
views: {
'menuContent': {
templateUrl: 'src/products/productDetails/productDetails.html',
controller: 'ProductDetailsCtrl'
}
},
params: {
productID: 0,
modelID: 0
}
})
$state.go('.', {param: someId});

How can I get AngularJS ui-router to respond correctly to a browser page refresh?

I have created an AngularJS application that uses ur-router. Here's a small sample of the config:
$locationProvider.html5Mode(true);
var admin = {
name: 'admin',
url: '/Admin',
views: {
'root': {
templateUrl: '/app/admin/partials/home.html',
},
'content': {
templateUrl: '/app/admin/partials/overview.html',
}
}
};
var adminContent = {
name: 'admin.content',
parent: 'admin',
url: '/:content',
views: {
'root': {
templateUrl: '/app/admin/partials/home.html',
},
'content': {
templateUrl: function (stateParams) {
return '/app/admin/partials/' + stateParams.content + '.html';
},
}
}
};
Everything is working when I start up the application, then go to the /Admin with a link and next I go to the reference link and it brings up the page:
http://xx.com/Admin/reference
When I click the browser back button it goes back to the previous page as expected.
However if I do a refresh now everything goes wrong. It forgets about ui-router and tries to find the page: xx.com/Admin/Reference
For reference I am using: #version v0.2.13
My index file looks like this:
<head>
<base href="/" />
Can someone give me some suggestions as to what I am doing wrong?
This is happening because you are using HTML5mode. You can either disable it or configure your server to handle it.
When you click a link on the page, the javascript changes the displayed url, but it does not actually navigate to the new url. When you refresh, the browser makes a request to the server for the new url. The server is treating it as a regular request, but it does not have any page at that url, so it returns a 404. You can configure the server to redirect any url to your main page so that this doesn't happen. When you refresh (with proper configuration), the server will send back index.html (or whatever your main page is) and the javascript can fetch the arguments out of the url.
This doc explains how to configure the server in ui-router. https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
You will also need a <base> tag so that angular can tell the difference between the url arguments and the rest of the url.
Example <base> tag:
If your site is http://www.example.com/ and you are on the Admin page (http://www.example.com/Admin), your base tag would look like <base href="http://www.example.com/">
For more info on the different routing modes in Angular see: https://docs.angularjs.org/guide/$location

Backbone pushState and Laravel 4 - Routes won't work

I've got a very simple setup of laravel 4 with 1 controller for trips.
Now another simple setup of Backbone with a Router and routes to regular routes like trips, trips/create. I want to use pushState: true to have nice URL but I can't seem to get it to work. When I try to reach the URLs it sends me to the page served by the server with my json data.
However, if I type: www.mysite.com/#trips I am "redirected" to www.mysite.com/trips and then my method for this specific route triggers.
Here's my Router:
App.Router = Backbone.Router.extend({
routes: {
'': 'index',
'trips': 'trips',
'trips/create': 'newTrip',
'trips/:id': 'showTrip'
},
index: function(){
},
trips: function(){
console.log('All trips') ;
},
newTrip: function(){
console.log('New trip') ;
},
showTrip: function(id){
console.log('trips id:' + id) ;
}
});
This is probably caused by the Backbone router not being able to match the URL to your Backbone routes. To debug, add this to your routes:
'*actions': 'defaultAction'
Then in the router add:
defaultAction: function(path) {
console.log('Route "' + path + '" not defined, redirecting to homepage!');
}
You will probably see that the path is different from anything in your routes. To fix this, you need to tell Backbone the root of your paths. You do this while activating pushstates.
Backbone.history.start({
pushState: true,
root: 'http://mydomain.com/myapplication/'
});
Hope this helps.

Backbone.js Pushstate: true not returning callback function

I am pretty new to backbone js and I am having some problem getting the pushstate functionality of my app to work. Here is an eg of my route:
var TodoRouter = new (Backbone.Router.extend({
routes: {
"": "index",
"item/add": "AddTodoItem",
"list/add": "AddTodoList"
},
AddTodoItem: function() {
//e.preventDefault();
alert("add new item");
},
AddTodoList: function(e) {
//e.preventDefault();
alert("add new list");
},
Start: function(){
//note: my directory structure is localhost/playground/todo/
Backbone.history.start({pushState: true, root: "/playground/todo/"});
},
initalize: function(){
},
index: function(){
var todoListView = new TodoListView({ collection: TodoItemCollection });
}
}));
Here is how I call my route:
$(function() {
TodoRouter.Start();
});
And lastly here is how I call a link:
New List
The problem that I am running into is that when I call the link, the page stays the same, no alert and the browser displays:
http://localhost/playground/todo/#list/add
Now here is the funny part, if I refresh the page, the url become:
http://localhost/playground/todo/list/add
and I get the alert. So I have a feeling I am missing a key point somewhere. Any help would be greatly appreciated!
You have pushState: true and that's why it preferred the slash / instead of hash #
Either change that or remove the hash
You're trying to use Backbone Routes and html5 pushState.
As the backbone documentation said:
"if you have a route of /documents/100, your web server must be able
to serve that page, if the browser visits that URL directly."
So if you want to trigger some functions through uri (localhost/webapp/#about) you just need to use Backbone Routes.
If you want to use Backbone Routes and pushState, you'll need a back-end to answer requests made to your readable url (localhost/webapp/about) and need to use backbone.navigate method to avoid the browser understand <a href="#someRoute"> as a html anchor.
here you can see a complete example
You can't trigger your route, because when pushState:true the href="#route" has the same behavior as a html anchor.

Resources