Jakemmarsh
Jakemmarsh

Reputation: 4661

AngularJS back button

I'm working on making an Android app using Phonegap and AngularJS. I'm attempting to create a button to be used as both a "cancel" and a "back" button, that will essentially just hit the browser's 'back' button.

Here's some sample HTML for the cancel button:

<a href="#" ng-click="goBack()" class="button--cancel weight--bold vertical-align--middle text-center">cancel</a>

And here is the controller for that page, with the goBack() button:

function NewOccasionCtrl($scope, $window) {
    $scope.$window = $window;
    $scope.goBack = function() {
      $window.history.back();
    };
}

This throws no errors, but also doesn't work... the emulator remains on the same page. Without the $scope.$window = $window it throws an error. I was hoping to achieve a functional 'back' button without having to create/use a directive, because as far as I understand those then implement templating and things I don't need/want.

Is there a way to do this? Thanks

Upvotes: 6

Views: 12183

Answers (2)

Brandon.Staley
Brandon.Staley

Reputation: 1802

I had an issue like this using phonegap and angular, $window.history.back() would not work. So I created a workaround.

$scope.urlHistory = [];

$scope.$on('$routeChangeSuccess', function () {
    if ($location.$$absUrl.split('#')[1] !== $scope.urlHistory[$scope.urlHistory.length - 1]) {
        $scope.urlHistory.push($location.$$absUrl.split('#')[1]);
    }
});

$scope.goBack = function () {
    $scope.urlHistory.pop();
    $location.path($scope.urlHistory[$scope.urlHistory.length - 1]);
};

Hope this help someone else.

Upvotes: 3

Jakemmarsh
Jakemmarsh

Reputation: 4661

I went with using a Directive to make the back functionality reusable. Here is my final code:

HTML:

<a href back-button>back</a>

Javascript:

app.directive('backButton', function(){
    return {
      restrict: 'A',

      link: function(scope, element, attrs) {
        element.bind('click', goBack);

        function goBack() {
          history.back();
          scope.$apply();
        }
      }
    }
});

Upvotes: 11

Related Questions