Angularjs 在 history.back() 上设置条件

Angularjs Setting a condition on history.back()

我目前有以下指令:

ngModule.directive('backButton', ['$window',
    function ($window) {
        return {
            restrict: 'A',
            scope: {},
            templateUrl: null,
            link: function (scope, element) {
                scope.comingFromIndex = function () {
                    ...
                };

                scope.backToIndex = function() {
                    $window.history.back();
                };
            }
        };
    }
]);

在我的模板中,我这样调用返回函数:

<a data-ng-click='backToIndex()' data-ng-hide='!comingFromIndex()'>Return To The Index</a>

功能comingFromIndex目前还没有实现,因为我不知道该怎么做。可以从索引以及其他页面访问此后退按钮所在的页面。就我而言,我希望仅当我来自索引时才显示此后退按钮。 我不确定最好的方法是什么,有什么建议吗?

您需要实现类似 ui-router 的东西作为您的路由提供者。

它向 rootScope 广播状态变化,您可以通过如下方式获取状态变化:

$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
   //check the "from" parameter - it will contain the url of the previous page.
});

试试下面的代码:(Reference)

控制器:

app.controller('trashCtrl', function ($scope, prevRoutePromiseGetter) {
    prevRoutePromiseGetter().then(function (prevRoute) {
        $scope.prevRoute = prevRoute || 'nowhere';
    });
});

解析对象:

resolve: {
    prevRoutePromiseGetter: function ($q, $rootScope) {
        var deferred = $q.defer();
        var dereg = $rootScope.$on('$routeChangeSuccess', 
            function(evt, next, prev) {
                dereg();
                deferred.resolve((prev.originalPath || '').substr(1));
            }
        );
        return function () {
            return deferred.promise;
        };
    }
}

我在那里找到了答案:

https://github.com/angular-ui/ui-router/issues/92

使用: angular.module('sample') .运行( [ '$rootScope', 函数 ($rootScope) { $rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams) { $rootScope.$previousState = from; }); }]);