AngularJS not setting location state with "skipReload" - angularjs

I am working on a site that is transitioning to Angular - it uses Angular for single page application navigation and a new feature I'm currently working on is written entirely in Angular.
The rest of the site takes navigation results and returns them through the SPA model, the feature I'm working on runs entirely in a single page, but in order to make links shareable and bookmarkable it changes the URL in relation to the current state of the page.
So when someone selects a new subsection of the new feature, we have some code like this in the subsection service:
function setLocationForSubsection(subsection) {
var path = subsection.id ? "subsections/" + subsection.id + "/" + subsection.urlSlug : "";
$location.path("/section/" + path).search({}).skipReload();
};
If they follow a link to elsewhere in the site ( which goes through a $stateProvider.state('all', { url: '*urlPath?id', controller... pattern ) it works correctly.
If they then hit the back button, they come back to the correct page and setLocationForSubsection is called. If they click on the same link outside of the subsection again, nothing happens.
So this course of action occurs:
/section/2/subsection-name <- works.
/news <- works
back button ( /section/2/subsection-name ) <- works
/news fails
As far as I can tell, the problem arises because the location path setting fails to push the location into the angular state in this situation, so as far as angular is concerned it is still on /news and so when I try to navigate back there, it doesn't pick it up as a navigation event. I have tried using $window.history.pushState(null, 'any', $location.absUrl()); manually, but it doesn't seem to make any difference. If I drop the skipReload call it works but reloads the contents of the page, which is superfluous in this case. I'm using that approach for now, but I would like to know if there is a better option.
Is there a way to tell angular that a state change has happened in this case?

Related

UI Router fails to update URL in address bar after successful state change

I'm building a small Angular app and I'm currently using ui-router.
I've hit a problem which looks awfully like a bug in ui-router but I can't be sure as I'm not that familiar with this library. When the user clicks on a specific link, although the correct view state gets loaded as expected, the URL in the address bar doesn't get updated.
I'm using ui-router's ui-sref directive to automatically generate the URL for the state. For example in the checklist list view I use the following code:
<a ui-sref="checklist-phase({ aircraftId: checklist.aircraft, checklistId: checklist.id, phaseSlug: checklist.phases[0].slug })" ng-bind="checklist.name"></a>
I've cut down my app and made it into a Plunker so the problem is hopefully reproducible by others. The issue can also be observed in this video: https://www.youtube.com/watch?v=EW9CFe6LfCw
Reproduction steps:
Go to http://run.plnkr.co/plunks/ZqMIYNU6abEAndAM5nx1/#/aircraft/1/checklists
Click the first link. Notice that the view updates to show the correct state, but the URL remains at /#/aircraft/1/checklists.
What is strange is that navigating back to this state by other means updates the URL perfectly. For example (assuming steps 1 and 2 above have been followed):
Scroll to the bottom and click the Next Phase link. Note that the state changes and the URL updates.
Scroll down on this new view and click Previous Phase. Note that the previous state reloads and this time the URL it updated correctly.
Am I using ui-router incorrectly or doing something else incorrectly to cause this behaviour?
Check here updated version
On your state 'check-lists' you provide ui-sref to 'checklist-phase'
<a ui-sref="checklist-phase({ aircraftId: ...
And the 'checklist-phase' is defined as a child state of 'checklist-detail'
.state('checklist-phase', {
parent: 'checklist-detail',
And the state 'checklist-detail' has controller which calls $state.go
.state('checklist-detail', {
controller: 'ChecklistDetailCtrl',
...
.controller('ChecklistDetailCtrl', function ($scope....
{
$state.go('checklist-phase', {
phaseSlug: checklistData.phases[0].slug
}, {
location: 'replace'
});
Do NOT do that... just remove the $state.go - because you are already navigating to the checklist-phase (see the first lines above) ... check it here

AngularJS - using Angular UI router - how to fetch the next content via AJAX without removing the current content

I'm using Angular UI router in my app. This is what I'm doing.
A main view contains a child view and a div container for "pagination"
By default, initially, a first set of contents is loaded
When a user clicks on "next page", next set of contents is loaded (with the URL also being changed to /content/2 (where 2 indicates the next page number)
All is working well, but each time the contents are loaded, it goes "blank" before it loads. So it seems like it's reloading the view (which is obvious).
What I would like to do is reload the content without having that "blank" page. How can I achieve this?
At first thought, I think you could you the same approach as infinite-scroll, which is what I'm using. So you make a GET request to the server to get new content and push it to the list on clicking 'next'. However, since the URL changes also. This will cause the controller to be reloaded. You can actually bypass this by setting reloadOnSearch to false.

Change route parameters without updating view

I'm currently trying to figure out how to change the route parameters without reloading the entire page. For example, if I start at
http://www.example.com/#/page
but update a name to be 'George', to change the route to be:
http://www.example.com/#/page/george
If I already had http://www.example.com/#/page/:name routed.
Without reloading the location. Can one just set $routeParams.name = "George" ?
Edit:
Alternatively, is there a way to update http://www.example.com/#/page?name=George without reloading or resetting the page?
Ok, after a lot of searching. I answered my own question.
I've discovered finding anything on the angular documentation is incredibly impossible, but sometimes, once it's found, it changes how you were thinking about your problem.
I began here: http://docs.angularjs.org/api/ng.$location
Which took me here: http://docs.angularjs.org/guide/dev_guide.services.$location
Which took me to this question: AngularJS Paging with $location.path but no ngView reload
What I ended up doing:
I added $location.search({name: 'George'}); To where I wanted to change the name (A $scope.$watch).
However, this will still reload the page, unless you do what is in that bottom StackOverflow link and add a parameter to the object you pass into $routeProvider.when. In my case, it looked like: $routeProvider.when('/page', {controller: 'MyCtrl', templateUrl:'path/to/template', reloadOnSearch:false}).
I hope this saves someone else a headache.
I actually found a solution that I find a little more elegant for my application.
The $locationChangeSuccess event is a bit of a brute force approach, but I found that checking the path allows us to avoid page reloads when the route path template is unchanged, but reloads the page when switching to a different route template:
var lastRoute = $route.current;
$scope.$on('$locationChangeSuccess', function (event) {
if (lastRoute.$$route.originalPath === $route.current.$$route.originalPath) {
$route.current = lastRoute;
}
});
Adding that code to a particular controller makes the reloading more intelligent.
You can change the display of the page using ng-show and ng-hide, these transitions won't reload the page. But I think the problem you're trying to solve is you want to be able to bookmark the page, be able to press refresh and get the page you want.
I'd suggest implementing angular ui-router Which is great for switching between states without reloading the page. The only downfall is you have to change all your routes.
Check it out here theres a great demo.

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.

Backbone.js: How to utilize router.navigate to manipulate browser history?

I am writing something like a registration process containing several steps, and I want to make it a single-page like system so after some studying Backbone.js is my choice.
Every time the user completes the current step they will click on a NEXT button I create and I use the router.navigate method to update the url, as well as loading the content of the next page and doing some fancy transition with javascript.
Result is, URL is updated which the page is not refreshed, giving a smooth user experience. However, when the user clicks on the back button of the browser, the URL gets updated to that of a previous step, but the content stays the same. My question is through what way I can capture such an event and currently load the content of the previous step and present that to the user? Or even better, can I rely on browser cache to load that previously loaded page?
EDIT: in particular, I'm trying something like mentioned in this article.
You should not use route.navigate but let the router decide which form to display based on the current route.
exemple :
a link in your current form of the registration process :
<a href="#form/2" ...
in the router definition :
routes:{
"form/:formNumber" : "gotoForm"
},
gotoForm:function(formNumber){
// the code to display the correct form for the current url based on formNumber
}
and then use Backbone.history.start() to bootstrap routing

Resources