Angular $ location.search替换浏览器历史记录

时间:2015-12-08 12:24:39

标签: javascript angularjs

有以下情况。我在' / drafts / URL,我去了草稿/ 101' (101是" id" params)。在这个控制器中,我想在没有页面刷新的情况下将101更改为102;我不知道我怎么做得对,所以我做了以下事情:

$location.search('new_id', message.id).replace()

这很好,但是当我按下'返回'按钮我去' / drafts?new_id = 102'网址,但我需要' /草稿'只要。我该怎么做?您可以为我的麻烦建议一些解决方案,或者我可以如何更改“ID&id”。完全没有'?new_id'。提前致谢。

1 个答案:

答案 0 :(得分:0)

这应该有所帮助。

谢谢刚刚提供的查询字符串参数。路由参数下面添加了更新。路线参数除了提供后退按钮之外没有直接的方法。 http://stackoverflow.com/questions/15175429/angularjs-getting-previous-route-path

<!DOCTYPE html>
<html ng-app="demo">
<head>
    <meta charset="UTF-8">
    <title>Ang</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script src="angular-route.js"></script>
    <script>
        var app = angular.module("demo",['ngRoute']);
        app.config(function($routeProvider){
            $routeProvider
            .when("/",{
                template:"<div>{{id}}</div>",
                controller:function($scope){
                    $scope.id = "Home";
                }
            })
            .when("/demo",{
                template:"<div>{{id}}</div>",
                controller:function($scope){
                    $scope.id = "Demo";
                }
            })  
            .when("/demo/:name",{
                template:"<a href='' ng-click='back();'>Back</a><div>{{id}}</div>",
                controller:function($scope, $route,$routeParams,$location,$rootScope){
                    // Do the following for routeParams
                    // But now the back will not work. 
                    // So you might have to use a back button or provide link to url:/demo      
                    if($routeParams.name === 'ganesh'){$route.updateParams({name:'test'});}
                    $scope.back = function(){
                        $rootScope.back();
                    }
                    // Do the following for Query Params  (/demo?name=...) and ('/demo?name')
                    //console.log($routeParams.name);
                    //$scope.id = $location.search().name;
                    //if ($location.search().name === 'test'){$location.search('name', 'ganesh').replace()};
                }
            })  
            .otherwise("/");        
        }).run(function ($rootScope, $location) {
                var history = [];
                $rootScope.$on('$locationChangeStart', function() {
                    history.push($location.$$path);
                });
                $rootScope.back = function () {
                    var prevUrl = history.length > 2 ? history.splice(-3)[0] : "/";
                    console.log(prevUrl);
                    $location.path(prevUrl);
                };
        });
    </script>
</head>
<body>
    <div ng-view></div>
</body>
</html>
相关问题