6

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

2
  • 1
    It makes no sense that $scope.$window = $window would be required. Jun 13, 2013 at 1:01
  • @KarlZilles then it probably isn't required... like I said, this doesn't work and I'm a bit confused as to how to approach this.
    – Jakemmarsh
    Jun 13, 2013 at 1:02

2 Answers 2

11

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();
        }
      }
    }
});
2
  • When i use this code i get a '$digest already in progress' error
    – PPPaul
    Mar 19, 2014 at 16:23
  • @PPPaul you can try using the strategy discussed here to avoid that error
    – Jakemmarsh
    Mar 19, 2014 at 18:52
3

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.