1

In my AngularJS application I have implemented a html button with a "go back"-functionality . In case the history is empty (because the user hasn't changed the path since page load) I want to hide/disable it.

Is there a way to detect if the history is empty with angular?

tmuecksch
  • 6,222
  • 6
  • 40
  • 61
  • Have you read about [$location](https://docs.angularjs.org/guide/$location) service of Angularjs? – AndrasCsanyi Jul 21 '15 at 20:29
  • However, this question is a possible [duplicate](http://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not). – AndrasCsanyi Jul 21 '15 at 20:31
  • In my opinion it's not, since the question is on how to do it "the angular-way". – tmuecksch Jul 21 '15 at 20:42
  • Good question. Only one alert: I had problems with go back function, because it can vary and sometimes your user doesn't go to where you need. I prefer href with a fixed destination (like "#/home") – Joao Polo Jul 22 '15 at 14:14

1 Answers1

5

You can even check $window service of angular js. It is completely same as window object of javascript.

The history object contains the URLs visited by the user (within a browser window).

The history object is part of the window object and is accessed through the window.history property.

If you want to see whether history is empty or not you should use

if( $window.history.length <= 1 ) {
  //Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1
  console.log("empty");
}

Please make sure you've injected $window service in your controller. Some couple of functions of history object are here. You can write more lines to detect browser first and after then apply your conditions in angular way. Please check this post

Community
  • 1
  • 1
Vineet
  • 4,525
  • 3
  • 23
  • 42
  • Thanks for your answer. Are you sure, checking for history.length === 0 is sufficient in order to make sure there weren't any visited URLs in this window before? Just asking because I thought I read somewhere it wouldn't be sufficient. EDIT: I already found the answer in the MDN article you have linked to. "You can determine the number of pages in the history stack by looking at the value of the length property" – tmuecksch Jul 21 '15 at 20:36
  • @tmuecksch please have a look on my edited answer. You can judge the history by using `<=1`. It will be good for all of the major browsers except IE or OPERA – Vineet Jul 21 '15 at 20:42
  • Vineet: Good to know. Thanks. – tmuecksch Jul 21 '15 at 20:48