angularjs 获取以前的路线路径 [英] angularjs getting previous route path

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

问题描述

<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'};
}

正如您在我的控制器中看到的,我对后退按钮的 url 和文本进行了硬编码(实际上我不需要使用图像的文本).通过这种方式,我发现在某些情况下后退按钮导航不正确.我无法使用 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.

所以我的问题是如何在控制器中获取先前的路由路径,或者是实现此目的的更好方法?

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 获取以前的路线路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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