DeividasJJ
DeividasJJ

Reputation: 125

Return previous content on browsers "Back" button click

I'm having a trouble while trying to return "old" content after clicking browsers back button.

Currently I'm trying to make a pagination with AngularJs and Symfony2:

app.js

var fcrApp = angular.module('fcrApp', ['ngRoute', 'fcrController']);

fcrApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $locationProvider.html5Mode(true);
}]);

controller.js

var fcrController = angular.module('fcrController', []);

fcrController.controller('MainController', function ($scope, $compile, $http, $location) {

    $scope.goToPage = function (host, path) {
        var ajaxUrl = changeUrl(host, path);
        getContent(ajaxUrl, path);
        changeBrowserUrl(path);
    }

    function changeBrowserUrl(path) {
        $location.path(path);
    }

    function changeUrl(host, path) {
        var newString = host.replace("www.", "");
        var newHost = newString.replace("http://", "http://ajax.");

        return newHost + path;
    }

    function getContent(link, path) {
        $http.get(link, { cache: true}).success(function (data) {
            angular.forEach(data.divs, function (value, key) {
                var compiledElement = $compile(value)($scope);
                $('#' + key).html(compiledElement);
            });

            $scope.title = data.title;
            if (data.robots) {
                $('meta[name=robots]').attr('content', data.robots);
            }

            $('html, body').animate({
                scrollTop: $("#" + data.scrollTo).offset().top
            }, 500);
        }).error(function () {
            location.assign(linkOld);
        });
    }
});

html:

 <a ng-click="goToPage(host, url)">page</a>

When page link is clicked, new html content is received over $http.get() and replaced with old one. The problem is that if I want to return with back button, url changes to old one too, but current content don't. Is there any solution to achieve that?

Thanks.

Upvotes: 0

Views: 1223

Answers (1)

iiminov
iiminov

Reputation: 979

I have solved the problem I had with my app. Something I noticed the other day is that every time I would press/go Back the browser would load data from cache.

Luckily in my case because I am loading my data using a service what I did is added one more header to be bundled with the request like so:

myApp.config(['$provide', '$httpProvider', function ($provide, $httpProvider) {
    // snip(...)
    // Prevent content creep on browser Back button
    $httpProvider.defaults.headers.common['Cache-Control'] = 'no-cache';
}]);

Now every time I press/go Back the browser is forced to reload data from the server.

Hope this helps someone else.

Upvotes: 1

Related Questions