angularjs获得previous路线路径 [英] angularjs getting previous route path

查看:168
本文介绍了angularjs获得previous路线路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<h1>{{header}}</h1>
<!-- This Back button has multiple option -->
<!-- In home page it will show menu -->
<!-- In other views it will show back link -->
<a ng-href="{{back.url}}">{{back.text}}</a>
<div ng-view></div>

在我的模块配置

  $routeProvider.
  when('/', {
    controller:HomeCtrl,
    templateUrl:'home.html'
  }).
  when('/menu', {
    controller:MenuCtrl,
    templateUrl:'menu.html'
  }).
  when('/items', {
    controller:ItemsCtrl,
    templateUrl:'items.html'
  }).
  otherwise({
    redirectto:'/'
  });

控制器

function HomeCtrl($scope, $rootScope){
  $rootScope.header = "Home";
  $rootScope.back = {url:'#/menu', text:'Menu'};
}

function MenuCtrl($scope, $rootScope){
  $rootScope.header = "Menu";
  $rootScope.back = {url:'#/', text:'Back'};
}

function ItemsCtrl($scope, $rootScope){
  $rootScope.header = "Items";
  $rootScope.back = {url:'#/', text:'Back'};
}

正如你可以在我的控制器看到我已经很难codeD后退按钮链接和文本(实际上是使用图像我不需要文本)。通过这种方式,我发现早在某些情况下,按钮导航不正确。我不能使用 history.back()怎么把我的后退按钮更改为在主视图菜单链接。

As you can see in my controllers I have hard coded the back button url and text (Actually I don't need the text as using an image). In this way I found back button navigate incorrectly in some cases. I cannot use history.back() coz my back button changes to a menu link in home view.

所以我的问题是如何获得在控制器中的previous路线路径或者是更好的方式来实现这一目标?

So my question is how do I get the previous route path in controllers or is better way to achieve this ?

我已经创建了我的问题的 Plunker 演示。请检查。

I have created a Plunker demonstration of my problem. Please check that.

推荐答案

本替代还提供了后退功能。

This alternative also provides a back function.

模板:

<a ng-click='back()'>Back</a>

模块:

myModule.run(function ($rootScope, $location) {

    var history = [];

    $rootScope.$on('$routeChangeSuccess', function() {
        history.push($location.$$path);
    });

    $rootScope.back = function () {
        var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
        $location.path(prevUrl);
    };

});

这篇关于angularjs获得previous路线路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆