Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 902
Jakemmarsh Avatar asked Jun 13 '13 00:06

Jakemmarsh


2 Answers

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();
        }
      }
    }
});
like image 111
Jakemmarsh Avatar answered Sep 28 '22 09:09

Jakemmarsh


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.

like image 41
Brandon.Staley Avatar answered Sep 28 '22 10:09

Brandon.Staley