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. Commented 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. Commented 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();
        }
      }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

When i use this code i get a '$digest already in progress' error
@PPPaul you can try using the strategy discussed here to avoid that error
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.