1

So I am relatively new to AngularJs and I am trying to figure out the best way for a tabController to remember what tab was previously clicked when switching to a new controller. So the situation would be I have 3 tabs. I click on tab 3 and then I click on something inside of it bringing me to a new controller and HTML template... What is the best way if I hit a "back" Button I created in that controller to remember exactly the state of it being the 3 tab.

I tried using $rootScope and then in each controller setting the tab number and setting the tabcontroller = $rootScope... but that was chaotic and too repetitive, and its not the right way.

This is not about $windoe.back(), this refers to coming up with a way that no matter where the navigation is the tab number is retained.

user2402107
  • 913
  • 5
  • 22
  • 43
  • Possible duplicate of [How to implement history.back() in angular.js](http://stackoverflow.com/questions/14070285/how-to-implement-history-back-in-angular-js) – Matthew Green Apr 11 '16 at 18:18
  • Dear anonymous user, did the solution provided in my answer help? Did you manage to accomplish what were you looking for? – iulian Apr 14 '16 at 08:05

1 Answers1

1

You can use a factory for this. In angular, a factory is a singleton, meaning only one instance of it exists for the whole project. Thus, by making something with it in one controller (and saving what you've did), you can access your changes in another controller.

angular.module('awesomeApp')
    .factory('tabHistoryFactory', function () {
        var tabHistory = {
            setPrevTab: function(tab) { tabHistory.prevTab = tab; },
            getPrevTab: function() { return tabHistory.prevTab; }
        };
        return tabHistory;
    });

Then, in your first controller you'll have to inject this factory and before changing to another tab, just save the tab you're on using tabHistoryFactory.setPrevTab(tab). Then, in your second controller, you can access your previous tab by using tabHistoryFactory.getPrevTab(). Similarly, you can customize the behavior of your tab history by implementing other functions alongside those two.

Good luck!

iulian
  • 5,494
  • 3
  • 29
  • 39