How to change the URL without reloading the page when back button is clicked in angularjs?

1.2k views Asked by At

I am using angularjs for my app. It contains a newsfeed. If user needs to view the particular news, he has to click on that particular news and it will redirect to that news. And after viewing the particular news, if user wants to go back to news feed(previous page), he has to click on the browser back button. So, in this case, if user clicks on the browser back button, the newsfeed page is reloading again. But, I dont want like this. I want to disable the reload and take the user to the place where he was before. I browsed a lot on this issue, but there was no absolute solution given. Please, help me out.

2

There are 2 answers

0
Sachin Verma On

you can take an anchor link and on click event of anchor call this javascript function

window.window.history.back(); 

here is the html code for it

   <input type="button" id="alnkBack"  onclick="window.window.history.back();" value="Back" class="button" />
0
Bibin On

When you go back, previous route will be triggered and data will be reloaded. If you want to prevent reloading, place a service in between and cache the data.

 $routeProvider.
  when('/loadFeeds',{
    controller:'LoadFeedCtrl',
    templateUrl:'pages/feeds.html',
    resolve:{
        initData : function(FeedService){
          return $q.all(
                    {
                        data: FeedService.load() 
                    }
                 );
        }
    }
  })

And in your FeedService, instead of making http call try to see the data is already available

.service('FeedService',function($q,$timeoute){
    this.feeds=[];
    this.load = function(){
           var deferred = $q.defer();
               $timeout(function(){
                  if(feeds.length===0){
                    this.feeds.push({title:'First','id':1})
                    this.feeds.push({title:'Second','id':2})
                    this.feeds.push({title:'Third','id':3})
                    this.feeds.push({title:'Fourth','id':4})
                  }
                  deferred.resolve(this.feeds);
               },2000);
          return deferred.promise;
    };
})

The timeout service could be replaced with $http or $resource. I used the timeout to simulate the delay